Mastering explain("executionStats"): COLLSCAN vs IXSCAN
Analyze MongoDB query execution plans: diagnose full collection scans (COLLSCAN), index seeks (IXSCAN), in-memory sorts (SORT), and selectivity ratios.
Index Traversal & IXSCAN vs COLLSCAN Execution Plan
Topic 30: Mastering explain("executionStats"): COLLSCAN vs IXSCAN
{
"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
The explain("executionStats") command reveals the internal physical plan chosen by the query optimizer and the actual runtime metrics: totalKeysExamined, totalDocsExamined, nReturned, executionTimeMillis, and the pipeline of execution stages (IXSCAN, FETCH, SORT, COLLSCAN).
2. Explain Like I'm 5 (Mental Model)
explain() is the X-ray machine for your queries: it shows whether the database read 5 index entries to find 5 results, or whether it had to scan through 1,000,000 records because an index was missing.
3. Real-World Architecture Example
Diagnosing a slow query searching for active accounts.
{
"stage": "COLLSCAN",
"nReturned": 4,
"totalDocsExamined": 1000000,
"executionTimeMillis": 850
}Ratio of 1,000,000 docs examined to 4 returned proves an urgent missing index on the status field.
4. MQL Implementation Steps
db.orders.find({ status: "pending", total: { $gt: 100 } })
.sort({ created_at: -1 })
.explain("executionStats");const stats = db.orders.find({ user_id: "u1" }).explain("executionStats").executionStats;
print("Returned: " + stats.nReturned);
print("Keys Examined: " + stats.totalKeysExamined);
print("Docs Examined: " + stats.totalDocsExamined);5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| COLLSCAN | Full Collection Scan: reads every physical document in the collection from disk/cache. Red flag in production. |
| IXSCAN -> FETCH | Standard indexed query: searches B-Tree (IXSCAN) and fetches matching documents (FETCH). |
| SORT stage | In-memory blocking sort: indicates missing index on the sort field. |
6. Deep Dive: The Index Selectivity Efficiency Ratio
The golden metric of MongoDB query tuning is the Selectivity Ratio: totalKeysExamined / nReturned. An ideal ratio is 1.0 (every key examined matched a returned document). If the ratio is 50 or 100+, the index is poorly selective or missing trailing compound predicates, forcing the engine to scan extraneous keys.
// Key indicators in explain output: // "totalKeysExamined": 10000, // "totalDocsExamined": 10000, // "nReturned": 5 -> Severe inefficiency! Ratio is 2000:1
7. Architectural Trade-offs
- •Uncovers exactly why queries are slow (missing index, in-memory sort, bad ESR order)
- •Provides definitive proof of covered queries (totalDocsExamined: 0)
- •Reveals candidate plans evaluated and rejected by the query optimizer
- •Running explain("executionStats") executes the query, consuming real server resources
- •Output JSON is verbose and requires trained architectural interpretation
8. Technical Interview Questions
It indicates severe index inefficiency. The query planner is scanning 10,000 index keys to find only 5 matching documents. This occurs when the leading fields of a compound index have low selectivity, or when filter predicates are missing from the index, forcing the engine to traverse wide ranges of non-matching B-Tree keys.
9. Staff-Level Ready Answer
"explain("executionStats") exposes the query optimizer's physical execution plan. Key metrics include totalKeysExamined, totalDocsExamined, and nReturned. The primary goal of query optimization is eliminating COLLSCAN and in-memory SORT stages, driving the ratio of totalDocsExamined / nReturned as close to 1:1 as possible."
10. Quick Knowledge Check
Which execution stage in an explain() winning plan indicates that MongoDB had to scan every document in the collection?