MongoDB Indexes
What Is Indexes?
An index is a small sorted data structure that lets MongoDB find documents without reading the whole collection. Without a useful index, a query performs a collection scan (COLLSCAN). Indexes are created with createIndex(). MongoDB always indexes _id; everything else is up to you. Indexes speed up reads but cost storage and add work to every write.
Why It Matters
| Reason | Benefit |
|---|---|
| Faster reads | Queries that would scan millions of documents can finish in milliseconds. |
| Efficient sorting | An index matching the sort order avoids an expensive in-memory sort. |
| Data integrity | Unique indexes enforce rules like one account per email. |
| Automatic cleanup | TTL indexes expire old sessions or logs without a cron job. |
How To Use It
- Insert some sample data into db.users with fields email, city, and age.
- Run db.users.find({ email: "[email protected]" }).explain("executionStats") and note COLLSCAN.
- Create an index: db.users.createIndex({ email: 1 }, { unique: true }).
- Run the same explain and confirm IXSCAN and low totalDocsExamined.
- Build a compound index such as { city: 1, age: -1 } for a query that filters by city and sorts by age.
- List indexes with getIndexes().
- Drop indexes you do not need with dropIndex() to save write cost.
mongosh Examples
// Before: collection scan
db.users.find({ email: "[email protected]" }).explain("executionStats")
// Unique single-field index
db.users.createIndex({ email: 1 }, { unique: true })
// After: look for IXSCAN in winningPlan
db.users.find({ email: "[email protected]" }).explain("executionStats")
// Compound index: equality (city), then sort (age)
db.users.createIndex({ city: 1, age: -1 })
db.users.find({ city: "Pune" }).sort({ age: -1 })
// TTL index: expire sessions after one hour
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
db.users.getIndexes()
db.users.dropIndex("city_1_age_-1") Edge Cases & Pitfalls
Too many indexes slow writes
Every insert and update must maintain each index. Keep only the ones your queries use.
Compound order matters
An index on { a: 1, b: 1 } supports queries on a, or on a and b, but generally not on b alone.
Unique index fails on existing duplicates
Creating a unique index errors if the collection already holds duplicate values. Clean them first.
Low-selectivity indexes help little
Indexing a field with only a few distinct values, like a boolean, rarely narrows results enough on its own.
Indexes use memory
Large indexes that do not fit in RAM cause disk reads. Check their size with db.collection.stats().
Cheat Sheet
| Topic | Detail |
|---|---|
| createIndex({ a: 1 }) | Single-field ascending index (-1 for descending) |
| createIndex({ a: 1, b: -1 }) | Compound index; field order matters |
| { unique: true } | Reject duplicate values for the indexed field(s) |
| { sparse: true } | Index only documents that contain the field |
| partialFilterExpression | Index only documents that match a filter |
| expireAfterSeconds | TTL index that deletes documents after a time |
| getIndexes() | List indexes on a collection |
| dropIndex(name) | Remove an index by name or key pattern |
| explain("executionStats") | Show the plan and how many documents were examined |
| IXSCAN vs COLLSCAN | Index scan is good; full collection scan is a red flag on big data |
Key Takeaways
Index the fields you filter, sort, and join on. For compound indexes, order fields as equality, sort, range, and confirm with explain("executionStats") that the plan uses IXSCAN.
Frequently Asked Questions
How do I create an index in MongoDB?
Use db.collection.createIndex({ field: 1 }). Use 1 for ascending and -1 for descending order.
How do I know if my query uses an index?
Append .explain("executionStats") to the query. IXSCAN in the winning plan means an index is used; COLLSCAN means a full scan.
Is _id indexed automatically?
Yes. Every collection has a unique index on _id that cannot be dropped.
What is a compound index?
An index on multiple fields. It supports queries that use a prefix of its fields and can also satisfy a sort in the same order.
Should I index every field?
No. Each index costs storage and write time. Index the fields your real queries filter and sort on.
What does a unique index do?
It rejects inserts or updates that would create a duplicate value for the indexed key, returning a duplicate key error.
Next: MongoDB Data Modeling
Continue the MongoDB learning path.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
8 people found this page helpful
