Indexes and explain()
With 10 documents, every query is instant. With 10 million, a query without the right index reads every document on disk: a collection scan. Indexes are the single biggest factor in MongoDB performance.
How an index helps
An index is a sorted list of one or more field values, each pointing to its document. To find email: 'x', MongoDB walks the sorted index (a B-tree) in a few steps instead of reading the whole collection. Every collection has an index on _id automatically.
The cost: indexes use memory and disk, and every write must update them. So you create the indexes your queries need, not one per field.
Seeing the plan with explain()
explain('executionStats') shows how MongoDB ran a query. Look at three things:
- winningPlan.stage:
COLLSCAN(read everything) orIXSCAN(used an index) - totalDocsExamined vs nReturned: ideally close to each other
- totalKeysExamined: index entries read
A COLLSCAN that examined 8 documents to return 2. Now create an index and run the same query:
Now it's an IXSCAN that examined exactly the 2 documents it returned.
The editor's planner is a simplified simulation of MongoDB's, so it's great for learning to read plans. On a real server,
explain()returns many more details.
Creating and managing indexes
Unique indexes
A unique index rejects duplicates, which is how you enforce "one account per email":
Missing fields count as null, so a second user without an email also clashes. If the field is optional, use a partial index that only covers documents that have it:
Compound indexes and the ESR rule
A compound index covers several fields, like { status: 1, createdAt: -1 }. It's sorted by the first field, then by the second within each value of the first.
Field order matters. MongoDB's guideline is ESR:
- Equality fields first (
status: 'shipped') - Sort fields next (
sort({ createdAt: -1 })) - Range fields last (
total: { $gt: 100 })
Equality on status, then results come out of the index already sorted by createdAt, so there's no in-memory SORT stage. Compare a sort the index can't help with:
A compound index also serves queries on its prefix: { status: 1, createdAt: -1 } helps queries on status alone, but not on createdAt alone.
Covered queries
If the filter and the returned fields are all in the index, MongoDB answers from the index without reading any documents. That's a covered query, the fastest kind:
totalDocsExamined: 0. (You must exclude _id, since it isn't in that index.)
Special index types
| Type | Use |
|---|---|
| Multikey | Created automatically when you index an array field: one entry per element |
| Text | Basic word search: createIndex({ title: 'text' }) and $text queries |
| TTL | Deletes documents automatically after a time: { expireAfterSeconds: 3600 } on a date field. Great for sessions and logs. |
| 2dsphere | Geospatial: "restaurants within 2 km" |
| Hashed | Even distribution for sharding |
| Wildcard | Indexes unknown or varying field names: { 'attributes.$**': 1 } |
// Sessions disappear 1 hour after createdAt (a real server's background job deletes them)
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })On MongoDB Atlas, Atlas Search and Vector Search indexes add full-text search and AI similarity search.
Index strategy in practice
- Index the fields your frequent queries filter and sort on; check them with
explain(). - Prefer one good compound index (following ESR) over several single-field ones.
- Remove unused indexes: on a real server,
db.collection.aggregate([{ $indexStats: {} }])shows how often each is used. - Keep your working set (hot data plus indexes) in RAM.
- Atlas's Performance Advisor suggests indexes based on slow queries.
Practice
- Run
explain('executionStats')ondb.products.find({ category: 'Electronics', price: { $lt: 100 } }). - Create the best compound index for it (think ESR), and run explain again.
- Make
skua unique field in a newinventorycollection, and prove it rejects duplicates.
1.In explain output, what does COLLSCAN mean?
2.Following ESR, which index suits find({ status: 'paid', total: { $gt: 50 } }).sort({ createdAt: -1 })?
3.Why might a unique index on email reject a second user who has no email at all?