Indexes dramatically speed up queries in MongoDB.
Types¶
- Single field
- Compound
- Multikey (arrays)
- Text
- Geospatial
- TTL (auto-delete)
Examples¶
db.orders.createIndex({userId:1,status:1,createdAt:-1})
db.sessions.createIndex({expiresAt:1},{expireAfterSeconds:0})
Explain¶
db.orders.find({userId:123}).explain('executionStats')
// COLLSCAN=bad, IXSCAN=good
- ESR: Equality, Sort, Range
- Partial indexes
- Covered queries
- Check unused ones
Indexing Strategy¶
The ESR rule (Equality, Sort, Range) determines the optimal field order in a compound index. Place equality match fields first, then sort fields, and finally range conditions. This minimizes the number of index keys examined.
Create partial indexes for collections where you query only a subset of documents — for example, {status: "active"}. This saves space and speeds up writes. Covered queries (queries whose results are entirely contained in the index) eliminate the need to read documents from disk. Regularly check unused indexes using $indexStats, because every index slows down writes and takes up disk space.
Indexes = Performance¶
Without indexes = collection scan. Always explain().