MongoDB Compound Index Design
Intermediatev1.0.0
Design optimal MongoDB compound indexes using the ESR rule — Equality, Sort, Range field ordering for maximum query coverage and minimal index overhead.
Content
Overview
A well-designed compound index can serve multiple query patterns with a single index. The ESR (Equality, Sort, Range) rule determines the optimal field order. Getting this wrong means MongoDB ignores your index entirely or uses it inefficiently.
Why This Matters
- -A COLLSCAN on 10M documents takes seconds; an index scan takes milliseconds
- -One compound index can serve many query patterns (prefix rule)
- -Wrong field order in compound indexes makes them useless for your queries
The ESR Rule
Step 1: Equality Fields First
Step 2: Sort Fields Second
Step 3: Range Fields Last
Step 4: Verify with explain()
Step 5: Covered Queries — No Document Fetch
Best Practices
- -Design indexes for your top 5-10 most frequent queries first
- -Use the prefix rule: one compound index serves multiple query patterns
- -Monitor index usage: db.collection.aggregate([{ $indexStats: {} }])
- -Remove unused indexes — each index slows writes by 5-10%
- -For sort operations, index sort direction must match query sort direction
- -Use partial indexes when queries always filter on a constant condition
Common Mistakes
- -Creating single-field indexes when a compound index would serve all queries
- -Putting range fields before sort fields (violates ESR rule)
- -Forgetting to exclude _id in projection for covered queries
- -Not checking explain() output after creating an index
- -Index key pattern sort direction not matching query sort direction
FAQ
Discussion
Loading comments...