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
Indexes = Performance¶
Without indexes = collection scan. Always explain().
mongodbindexesperformance