Compound Indexes & The ESR (Equality, Sort, Range) Rule
The Golden Rule of MongoDB Indexing: Order compound index attributes by Equality first, Sort second, and Range third to minimize scanned index keys.
Index Traversal & IXSCAN vs COLLSCAN Execution Plan
Topic 22: Compound Indexes & The ESR (Equality, Sort, Range) Rule
{
"queryPlanner": {
"winningPlan": {
"stage": "FETCH",
"inputStage": {
"stage": "IXSCAN",
"indexName": "role_1_country_1",
"isMultiKey": false,
"direction": "forward"
}
}
},
"executionStats": {
"nReturned": 2,
"executionTimeMillis": 1,
"totalKeysExamined": 2,
"totalDocsExamined": 2
}
}1. Formal Definition & Architecture Intent
A Compound Index contains multiple fields in a defined sequence. The ESR (Equality, Sort, Range) Rule dictates that optimal compound index column ordering is: 1. Equality fields first (exact matches), 2. Sort fields second (satisfying sort order without in-memory sorting), and 3. Range fields last ($gt, $lt, $in).
2. Explain Like I'm 5 (Mental Model)
Think of a library catalog. If you want books where Language = English (Equality), sorted by Year (Sort), and Price < $20 (Range): sorting the shelf by Language first, then Year, then Price lets you walk straight to the shelf and read in order without backtracking.
3. Real-World Architecture Example
Optimizing an e-commerce order query: category = "Hardware", sorted by created_at DESC, total > 500.
{
"category": "Hardware",
"created_at": "2026-03-01",
"total": 1250
}Optimal compound index according to ESR: { category: 1, created_at: -1, total: 1 }.
4. MQL Implementation Steps
db.orders.createIndex({ category: 1, created_at: -1, total: 1 });db.orders.find({
category: "Hardware",
total: { $gt: 500 }
}).sort({ created_at: -1 });5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| E - Equality | Place exact match fields first to immediately narrow the B-Tree search space to a contiguous range. |
| S - Sort | Place sort fields next to avoid in-memory blocking sorts (SORT stage) and the 100MB RAM sort limit. |
| R - Range | Place inequality ($gt, $lt, $in) fields last. Placing a range field before a sort field breaks index-assisted sorting. |
6. Deep Dive: Why Placing Range Before Sort Breaks the Index Sort
If you index { total: 1, created_at: -1 } and query { total: { $gt: 500 } }.sort({ created_at: -1 }), the B-Tree scan visits multiple total values (501, 502, ...). Within each total value, created_at is sorted; however, across different total values, created_at is completely unsorted! MongoDB is forced to load all matching records into memory and run a blocking SORT algorithm.
// ❌ Flawed order (Range before Sort):
db.orders.createIndex({ total: 1, created_at: -1 }); // Incurs SORT stage!
// ✅ Correct ESR order:
db.orders.createIndex({ created_at: -1, total: 1 }); // Non-blocking!7. Architectural Trade-offs
- •Eliminates in-memory sort stages (SORT), preventing 100MB RAM sort exceptions
- •Achieves optimal index selectivity: keysExamined precisely matches nReturned
- •A single compound index can also satisfy queries filtering on its prefix attributes
- •Large compound indexes consume significant RAM cache space
- •Cannot be traversed backwards if sort directions differ in opposing vectors
8. Technical Interview Questions
The ESR rule orders compound index fields: Equality, Sort, then Range. If a Range field is placed before a Sort field, the index scan traverses multiple disjoint keys for the range predicate. Because documents across those disparate range values are not sorted relative to each other, the database cannot use the index to satisfy the sort and must execute an expensive in-memory SORT stage.
9. Staff-Level Ready Answer
"The ESR rule states that compound indexes should be ordered: Equality fields first to partition the search space, Sort fields second to avoid in-memory sorting, and Range fields last. Violating ESR by placing Range before Sort triggers an in-memory blocking SORT stage."
10. Quick Knowledge Check
Which compound index optimally satisfies: db.users.find({ country: "US", age: { $gte: 21 } }).sort({ signupDate: -1 })?