Lesson 4 of 9 · 20m
Explain Before You Tune
Reading `explain()` output is the difference between database performance work and superstition-driven index creation.
A senior MongoDB engineer's first move is never "add an index." It is explain("executionStats"). The output tells you whether the query scanned the collection, which index won, how many keys and documents were inspected, and whether sorting happened in memory. Everything else is guesswork.
The shape of a useful explain
db.orders.find({
tenantId: ObjectId("665f0a9381c4b7c8e89a2b11"),
status: "paid",
createdAt: { $gte: ISODate("2026-11-01T00:00:00Z") }
}).sort({ createdAt: -1 }).limit(50)
.explain("executionStats")The fields that matter first:
stage:COLLSCANmeans no usable index for the predicate.executionStats.nReturned: documents returned.totalKeysExamined: index entries inspected.totalDocsExamined: full documents fetched.executionTimeMillis: server execution time, not client latency.
A healthy selective query often examines roughly the number of keys it returns, plus range-scan overhead. A query returning 50 documents after examining 180,000 is telling you exactly where the pain is.
Understand the winning plan tree
A compact example:
LIMIT
└── FETCH
└── IXSCAN { tenantId: 1, status: 1, createdAt: -1 }IXSCAN searched the index; FETCH loaded documents because the query needed fields not present in the index. SORT in the tree means MongoDB had to materialize and sort results itself. In-memory sorts are capped at 100 MB unless allowDiskUse applies, and they are often the hidden reason pagination falls over.
Compare plans before believing them
MongoDB's query planner samples candidate plans and caches a winner. Data distribution can change enough that yesterday's winner becomes today's regression. If behavior is bizarre, inspect the execution stages and rejected-plan information in the explain output, then test candidate indexes explicitly:
db.orders.find({ status: "paid" }).hint({ status: 1, createdAt: -1 })hint() is a diagnostic scalpel, not a lifestyle. Shipping permanent hints because you do not understand the planner just moves the mystery into the future.
Field notes
COLLSCANis not automatically evil; scanning a 400-document config collection is fine. Scanning 40 million orders is not.- High
totalDocsExaminedwith lownReturnedmeans poor selectivity or missing index coverage. totalKeysExaminedmuch larger thannReturnedmeans broad ranges or poor index ordering.- Always explain with realistic parameter values. A selective tenant ID and the string
"all"produce different lives.
Was this lesson helpful?