MongoDB Index Internals: B-Tree Page Splits, the ESR Rule, and Plan Cache Invalidation
A MongoDB query that returns one document from a collection of 10 million can execute in under 1ms — or in 8 seconds. The difference is entirely determined by whether the query planner finds a B-Tree index path that narrows the scan to the matching key range before fetching any documents. When no suitable index exists, MongoDB executes a COLLSCAN: every document in the collection is read from WiredTiger cache (or from disk if cache-evicted), deserialized, and evaluated against the filter predicate. At 10 million documents averaging 2KB each, a COLLSCAN reads approximately 20 GB of uncompressed data. At NVMe SSD throughput of 3 GB/s with a warm WiredTiger cache, that is 6.7 seconds minimum — for a query that fetches a single document.
Understanding why this happens requires understanding how WiredTiger’s B-Tree index is physically organized, how the query planner selects among competing index paths, and how the plan cache stores and invalidates those decisions. Without this understanding, engineers add indexes in the wrong order, fail to satisfy sort stages, and create maintenance overhead from index proliferation — without improving the queries that actually matter.
Situation
MongoDB uses WiredTiger’s B-Tree storage format for all indexes. A B-Tree index is a balanced tree of pages: internal (non-leaf) pages hold key-pointer pairs that route traversal down the tree; leaf pages hold the actual index entries — the indexed field value(s) and the corresponding document identifier (RecordId pointing to the WiredTiger row in the collection file).
| Index Architecture | Key Ordering | Multi-Field Support | Array Field Support | Query Planner Interaction |
|---|---|---|---|---|
| WiredTiger B-Tree (MongoDB single-field) | Sorted ascending or descending on one field | No — one field per index | Yes — multikey index (one entry per array element) | Planner uses index for equality, range, and sort on the indexed field |
| WiredTiger B-Tree (MongoDB compound) | Sorted on field 1, then field 2, then field 3… lexicographically | Yes — up to 32 fields per compound index | Yes — at most one array field per compound index | Planner uses index for all queries matching any prefix of the index fields |
| WiredTiger B-Tree (MongoDB text/hashed) | Text: inverted index on stemmed tokens; Hashed: uniform distribution of hash values | Text: fields in the text index; Hashed: single field | Text: array of string elements; Hashed: no array support | Planner uses text index for $text queries; hashed for shard key equality; neither supports range queries |
The query planner is MongoDB’s cost-based optimizer. For each query, it generates candidate plans from available indexes and selects the plan with the lowest estimated cost — measured in “works” (units of work to scan index and fetch documents). When multiple indexes could satisfy a query, MongoDB runs the candidates in parallel using a “plan tournament” — each candidate executes up to a threshold of works; the first candidate to complete or the one completing the most work within the threshold wins and is cached for future identical query shapes.
The Problem
The compounding nature of B-Tree index traversal creates three failure modes that explain the majority of MongoDB performance regressions as collections grow:
The COLLSCAN growth trap. A collection with no index on a query field forces a full scan. At 10,000 documents the scan takes 5–20ms — fast enough to pass QA. At 1 million documents it takes 500ms–2s. At 10 million documents, latency becomes seconds. The transition from “acceptable” to “production incident” happens between 500K and 2M documents in most applications — precisely when traffic has also grown and the incident is most disruptive.
The wrong-order compound index. An engineer adds a compound index {userId: 1, createdAt: -1} to support a query db.orders.find({status: "shipped"}).sort({createdAt: -1}). This index cannot be used for this query: status is not in the index prefix. An IXSCAN on {userId: 1, createdAt: -1} would require scanning the entire index to find documents where status == "shipped" — the planner correctly recognizes this is worse than a COLLSCAN and does not use the index.
The in-memory sort abort. A query uses an IXSCAN for filtering but the sort field is not in the index. MongoDB buffers the filter results, then sorts in memory. If the result set before sorting exceeds 100MB (the allowDiskUse default threshold), MongoDB aborts with: Sort exceeded memory limit of 104857600 bytes. This failure mode appears suddenly in production when a previously filtered result set grows past the threshold.
How do you determine, from first principles, what compound index field order satisfies a query’s filter, sort, and range requirements simultaneously — and how do you verify the planner is using the index you intended?
B-Tree Page Splits: Why Index Write Cost Scales Non-Linearly
Understanding B-Tree page splits explains why write-heavy workloads with many indexes experience disproportionate write amplification, and why index field order affects both read and write performance.
WiredTiger B-Tree pages have a default maximum size of 32KB for leaf pages. When an index insert causes a leaf page to exceed 32KB, WiredTiger splits the page: the leaf page is divided into two new leaf pages, and a new key-pointer entry is added to the parent internal page pointing to the newly created right leaf. If the parent internal page also exceeds its maximum size, it splits too — propagating up the tree in a worst case that reaches the root.
Page splits have two operational consequences:
Write amplification. A single index insert can trigger multiple page writes: the split leaf page(s) and the updated internal page(s). On a collection with 10 indexes, each document insert can trigger up to 10 × (split factor) page writes — B-Tree maintenance multiplies write I/O beyond the raw document count.
Sequential vs. random insert patterns. Index entries for a monotonically increasing field (like _id: ObjectId() or createdAt: new Date()) are always appended to the rightmost leaf page. The rightmost page fills and splits, then the new rightmost page fills and splits — a repeating sequential write pattern that generates minimal B-Tree structural rebalancing. By contrast, inserts on a randomly distributed field (like a hashed UUID) cause page splits across the entire B-Tree — a random write pattern that generates more I/O per insert. This is why MongoDB recommends ObjectId-based shard keys for time-series collections and why monotonic fields as leading index keys minimize write amplification.
In Practice: The ESR Rule and Plan Cache Mechanics
The ESR rule — mechanical derivation. The ESR rule (Equality fields first, Sort fields second, Range fields last) is not an arbitrary convention. It derives from how the B-Tree stores multi-field keys and how the planner traverses them:
A compound index on {status: 1, createdAt: -1, amount: 1} stores keys sorted first by status (ascending), then within each status value by createdAt (descending), then within each (status, createdAt) pair by amount (ascending).
For a query find({status: "shipped", amount: {$gt: 100}}).sort({createdAt: -1}):
- Equality on
status: The B-Tree traversal seeks directly to the contiguous key range wherestatus == "shipped"— an O(log N) point lookup regardless of collection size. - Sort on
createdAt: Within thestatus == "shipped"range, keys are already stored in descendingcreatedAtorder. The index scan returns keys in the required sort order — no in-memory sort stage needed. - Range on
amount: Within each(status, createdAt)pair,amountis stored sorted — but sincecreatedAtvalues are unique, theamountdimension provides no meaningful narrowing. Range fields go last because they cannot be used for index ordering after a range boundary is set.
If you reverse the order and put the range field first — {amount: 1, status: 1, createdAt: -1} — the B-Tree scan must traverse the entire key range where amount > 100 (which may be 80% of the index) scanning for status == "shipped" values — eliminating the benefit of the equality condition’s O(log N) point lookup.
Reading explain() output. The definitive diagnostic:
// Full execution stats — use this, not just explain() without args
db.orders.find({status: "shipped", amount: {$gt: 100}})
.sort({createdAt: -1})
.explain("executionStats")
Fields that matter:
// In the explain output, look for these paths:
{
"queryPlanner": {
"winningPlan": {
"stage": "FETCH", // Good — wrapping an IXSCAN
"inputStage": {
"stage": "IXSCAN", // Good — index scan used
"indexName": "status_1_createdAt_-1_amount_1",
"direction": "forward",
"indexBounds": { // Verify the bounds match your query
"status": ["[\"shipped\", \"shipped\"]"],
"createdAt": ["[MaxKey, MinKey]"], // Full range — sort direction
"amount": ["(100.0, inf.0]"] // Range filter
}
}
},
"rejectedPlans": [...] // Check what the planner rejected and why
},
"executionStats": {
"nReturned": 42, // Documents returned to client
"totalDocsExamined": 42, // Should equal nReturned for perfect index selectivity
"totalKeysExamined": 43, // Should be close to nReturned; much higher = poor selectivity
"executionTimeMillis": 3, // Wall clock time
"stage": "SORT" // RED FLAG — in-memory sort; should not appear if ESR is correct
}
}
totalDocsExamined vs nReturned: If totalDocsExamined is 10× nReturned, the index is scanning far more documents than it returns — poor selectivity, often indicating a low-cardinality leading field or a missing equality condition.
SORT stage in winning plan: If the winning plan includes a SORT stage above the IXSCAN, the index does not cover the sort. The query is sorting in memory — which aborts at 100MB.
Plan cache mechanics and invalidation. MongoDB caches winning plans per query shape (the structure of the query without the literal parameter values). The cache stores the winning plan from the plan tournament. Queries with the same shape reuse the cached plan without re-running the tournament.
Plan cache invalidation occurs automatically when:
- An index is added or dropped on the collection
- The collection is rebuilt or compacted
- The plan cache is explicitly cleared:
db.collection.getPlanCache().clear() - MongoDB detects that the cached plan is performing significantly worse than expected (replanning triggered by the “works” threshold)
After a new index is added, the plan cache is cleared for that collection — the next queries re-run the plan tournament against all available indexes. This means a new index can cause a temporary latency increase as plan tournaments run for each distinct query shape.
$indexStats — finding unused indexes:
// Which indexes have never been used (candidates for removal)?
db.orders.aggregate([
{$indexStats: {}},
{$project: {
name: 1,
ops: "$accesses.ops",
since: "$accesses.since",
unusedDays: {$divide: [{$subtract: [new Date(), "$accesses.since"]}, 86400000]}
}},
{$match: {ops: {$lt: 100}}}, // Fewer than 100 accesses since last restart
{$sort: {ops: 1}}
])
Indexes with zero accesses.ops since the last mongod restart are candidates for removal. Each unused index consumes WiredTiger cache space (index pages are loaded on write, even if never used for reads) and adds write amplification to every insert, update, and delete on the collection.
Compound index key compression. WiredTiger uses prefix key compression for B-Tree index pages by default. For a compound index {status: 1, createdAt: -1} where many documents share the same status value, WiredTiger stores the status prefix once and stores only the createdAt suffix for subsequent entries with the same status. This prefix compression reduces index on-disk size by 40–80% for low-cardinality leading fields — but it also means that the in-memory uncompressed representation of the index is significantly larger than the compressed on-disk representation. Index sizing using db.collection.stats().indexSizes returns the compressed on-disk size; multiply by 2–4× for the actual WiredTiger cache footprint.
Multikey index internals. When a field contains an array, WiredTiger creates one index entry per array element. A document with tags: ["mongodb", "indexes", "performance"] creates 3 index entries under a {tags: 1} index. This has two implications:
// Check if an index is multikey (expanded from array fields)
db.collection.getIndexes()
// Look for "multiKey: true" in the index flags
// Or query:
db.collection.aggregate([{$indexStats: {}}, {$project: {name: 1, "spec.key": 1}}])
Multikey expansion inflates index size proportionally to average array cardinality. A collection where each document has 20 tags has a {tags: 1} index that is 20× larger than the equivalent single-value field index. Index size estimation must account for average array length for multikey indexes.
Where It Breaks
| Failure Mode | Root Cause | Production Blast Radius | Mitigation |
|---|---|---|---|
| COLLSCAN at production data volume — passed QA | Query lacks a covering index; collection was small during testing and masked the O(N) scan cost | At 10M documents, query latency is seconds; at 50M documents, minutes; collection scan holds shared collection lock on older MongoDB versions, blocking other operations | Run db.collection.explain("executionStats").find(query) against a production-representative data volume; any COLLSCAN or totalDocsExamined >> nReturned must be resolved before launch |
| In-memory sort abort — Sort exceeded memory limit | Compound index does not cover the sort field (sort field not in index, or in wrong position after a range field); result set before sorting exceeds 100MB | Query aborts with error: Sort exceeded memory limit of 104857600 bytes; if allowDiskUse: true is set, sort spills to disk and operation takes 10–100× longer | Add sort field to the compound index in ESR order; if the sort must remain in-memory for performance reasons, reduce the pre-sort result set with tighter equality filters; for analytics, accept disk-based sort with allowDiskUse: true on a secondary |
| Plan cache selects wrong index after new index added | Plan tournament runs on new query shapes after index addition; for some shapes, the planner selects a new index that is suboptimal due to stale statistics or low-work-threshold tournament | Latency regression on existing queries after an index is added to speed up a different query | Monitor query latency after any index addition; use $comment on critical queries to identify them in the slow query log; if the planner selects wrong plan, use hint() to force the correct index while the planner accumulates better statistics |
| Index proliferation — write amplification exceeds read benefit | Teams add an index for every new query without removing superceded indexes; a collection with 20 indexes has 20× write amplification per document operation | Write throughput drops as insert/update latency grows with index count; during high-write events (bulk imports, migrations), index maintenance creates I/O saturation | Audit indexes quarterly using $indexStats; remove any index with ops < 100 since last restart; prefer compound indexes that cover multiple query patterns over single-field indexes for each |
| B-Tree page splits during bulk insert — write stall | Bulk inserting randomly distributed documents (e.g., random UUIDs) into a collection with compound indexes causes page splits across the entire B-Tree simultaneously; eviction and checkpoint compete for I/O | Bulk import throughput drops 10–100× compared to sequential inserts; mongod CPU spikes on reconciliation threads | For bulk imports, use monotonically increasing _id (ObjectId or sequential integer) to minimize page splits; temporarily drop and rebuild secondary indexes after bulk import using db.collection.createIndex() with background: true |
| Sparse index misuse — documents excluded silently | A sparse index on a field that is sometimes absent from documents skips documents where the field is missing; queries that filter on this field using sparse index miss those documents | Data integrity failure: query returns fewer results than actually exist; no error is thrown | Use sparse indexes only when the absent-field documents are correctly excluded from the query domain; for nullable-equivalent fields, use a partial index with an explicit filter expression instead: {key: 1} with {partialFilterExpression: {key: {$exists: true}}} |
| Multikey compound index — array fields rejected | Attempting to create a compound index where two or more fields contain arrays; MongoDB/WiredTiger rejects this with MongoServerError: cannot index parallel arrays [field1] [field2] | Index creation fails; the application fallback (COLLSCAN or single-field index) may be inadequate for the query | Design document schema to avoid having two parallel array fields that both need indexing in the same compound index; refactor the document structure to embed the relationship within a single array of subdocuments |
| Covered query not covered — projection omitted | Engineers design a compound index to cover a query but forget to include the projected fields in the index key; MongoDB must fetch the full document from the collection to apply the projection | The IXSCAN stage is present but followed by a FETCH stage for each document — double I/O versus a true covered query that serves results from index pages alone | Verify covered query by checking for absence of FETCH stage in explain output; the covered index must include all fields in filter, sort, AND projection; _id must be explicitly excluded ({_id: 0}) if not in the index to avoid a FETCH for _id |
2024 Index Optimizer and Vector Search Update
The 2023 query engine improvements (shipping in MongoDB’s 7.x release series, GA August 2023) made the plan tournament more accurate for compound indexes on selective fields. The improved cost model accounts for index key distribution statistics more accurately, reducing cases where the planner selects a suboptimal index due to underestimating the selectivity of an equality filter on a compound index prefix.
The 7.x release also introduced $rankFusion and $vectorSearch index types for Atlas Vector Search — hybrid indexes that combine BM25 text scoring with ANN vector similarity in a single query plan. These index types operate on a separate FAISS-based index structure, not WiredTiger B-Trees, and are not subject to the ESR rule or the plan cache mechanics described above.
The explain("queryPlanner") output format was enhanced in the 2023 release cycle to include planSummary at the top level — a human-readable one-line description of the winning plan (e.g., "IXSCAN { status: 1, createdAt: -1 }") that is easier to scan in monitoring dashboards than the full JSON plan tree.
What to Do Next
- Problem: MongoDB index selection is a function of compound index field order, query filter structure, and sort direction; when the index field order does not match the ESR pattern for the query, the planner either cannot use the index or uses it inefficiently — returning to full collection scan behavior at scale.
- Solution: Apply the ESR rule to every compound index: equality-filter fields first, sort fields second, range-filter fields last; verify with
.explain("executionStats")that the winning plan shows IXSCAN (not COLLSCAN), thattotalDocsExaminedequalsnReturned, and that noSORTstage appears above the IXSCAN. - Proof: The B-Tree key storage format — sorted lexicographically on field 1, then field 2, then field 3 — means that a sort on field 2 is only index-ordered within a fixed field 1 value; placing a range condition on field 1 before a sort field on field 2 destroys the sort ordering within the scanned range, forcing an in-memory sort stage regardless of whether the index exists.
- Action: Run
db.collection.aggregate([{$indexStats: {}}])on your three highest-traffic collections and identify any index with fewer than 100accesses.opssince the last mongod restart — those are candidates for removal and their write amplification cost is pure overhead with no read benefit.
Sources to Verify
- MongoDB Manual — Indexing Strategies and the ESR Rule: https://www.mongodb.com/docs/manual/tutorial/create-indexes-to-support-queries/
- MongoDB Manual — explain() Output Reference — executionStats Fields: https://www.mongodb.com/docs/manual/reference/explain-results/
- WiredTiger B-Tree Storage Architecture — Key Ordering and Prefix Compression: https://source.wiredtiger.com/develop/arch-btree.html
- MongoDB Manual — $indexStats Aggregation Stage: https://www.mongodb.com/docs/manual/reference/operator/aggregation/indexStats/
- MongoDB Manual — Multikey Indexes and Compound Index Restrictions: https://www.mongodb.com/docs/manual/core/index-multikey/
- MongoDB Manual — Plan Cache Reference and Invalidation Conditions: https://www.mongodb.com/docs/manual/reference/method/db.collection.getPlanCache/
- WiredTiger B-Tree Page Split Mechanics — WiredTiger Source Architecture Documentation: https://source.wiredtiger.com/develop/arch-schema.html