Reference · Cheat sheet

The planner & explain()

Lesson 0004 distilled — Mongo races plans instead of costing them; read the stage tree and the examined:returned ratio. Built to print.

From lesson 0004Context: MongoDB current (7.0/8.0+)

The keystone

The classic planner races candidate plans in a short trial and keeps the one with most results, least work — an empirical run-off, not a cost-from-stats estimate.

(8.3+ adds a cost-based ranker as a backup.)

Verbosities

queryPlanner (default) — intended plan, doesn't run.

executionStats — runs it, real counts. Use this to tune.

allPlansExecution — adds losers' trial data.

Stages (read the tree)

COLLSCAN = read every doc (bad). IXSCAN = walk index keys.

FETCH = go get the document. SORT = in-memory sort (index didn't supply order).

IXSCAN + no FETCH = covered query. winningPlan / rejectedPlans.

The #1 skill — examined:returned

nReturned vs totalKeysExamined vs totalDocsExamined.

Near 1:1 = efficient. Big gap = reading lots to emit little (wrong/broad index or COLLSCAN).

Cousin of Postgres estimated-vs-actual rows.

Plan cache

Winner cached by query shape, reused. States: Missing → Inactive → Active.

Cleared by any DDL (create/drop/hide index), LRU, restart.

explain() bypasses the cache and creates no entry.

SQL vs Mongo

Choose plan: cost-from-stats → race. #1 tell: est-vs-actual → examined-vs-returned.

Real numbers: EXPLAIN ANALYZE → explain("executionStats") (and it's safe on writes).