Skip to content
LESSON 22 / 50Advancedindexing

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.

Interactive Engine Simulator

Index Traversal & IXSCAN vs COLLSCAN Execution Plan

Topic 22: Compound Indexes & The ESR (Equality, Sort, Range) Rule

Execution Stage
IXSCAN + FETCH
B-Tree leaf seek
Documents Examined
2
O(log N) lookup
Keys Examined
2
Index keys inspected
Query Latency
0.3 ms
WiredTiger execution time
Explain Plan Output Summary:
{
  "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.

Sample BSON Documents:
Collection: db.orders
{
  "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

Step 1: Create compound index following ESR order
db.orders.createIndex({ category: 1, created_at: -1, total: 1 });
Equality: category, Sort: created_at, Range: total.
Step 2: Query using ESR index
db.orders.find({
  category: "Hardware",
  total: { $gt: 500 }
}).sort({ created_at: -1 });
Guarantees totalKeysExamined === nReturned and stage is SORT-free!

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
E - EqualityPlace exact match fields first to immediately narrow the B-Tree search space to a contiguous range.
S - SortPlace sort fields next to avoid in-memory blocking sorts (SORT stage) and the 100MB RAM sort limit.
R - RangePlace 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!
Production Warning: If in-memory sort exceeds 100MB, MongoDB aborts the query with an error unless allowDiskUse: true is set.

7. Architectural Trade-offs

Advantages
  • •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
Disadvantages & Gotchas
  • •Large compound indexes consume significant RAM cache space
  • •Cannot be traversed backwards if sort directions differ in opposing vectors

8. Technical Interview Questions

Q1: Explain the ESR rule in MongoDB and what happens if you place a Range field before a Sort field in a compound index?

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 })?