Skip to content
LESSON 30 / 50Advancedindexing

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.

Interactive Engine Simulator

Index Traversal & IXSCAN vs COLLSCAN Execution Plan

Topic 30: Mastering explain("executionStats"): COLLSCAN vs IXSCAN

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

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.

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

Step 1: Run explain with full execution statistics
db.orders.find({ status: "pending", total: { $gt: 100 } })
  .sort({ created_at: -1 })
  .explain("executionStats");
Inspect executionStats block for runtime metrics.
Step 2: Extract key performance indicators
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);
Optimal queries maintain totalDocsExamined === nReturned.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
COLLSCANFull Collection Scan: reads every physical document in the collection from disk/cache. Red flag in production.
IXSCAN -> FETCHStandard indexed query: searches B-Tree (IXSCAN) and fetches matching documents (FETCH).
SORT stageIn-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
Production Warning: A query with high totalDocsExamined causes buffer cache thrashing and ticket exhaustion.

7. Architectural Trade-offs

Advantages
  • •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
Disadvantages & Gotchas
  • •Running explain("executionStats") executes the query, consuming real server resources
  • •Output JSON is verbose and requires trained architectural interpretation

8. Technical Interview Questions

Q1: In explain("executionStats"), what does it signify when totalKeysExamined is 10,000 but nReturned is only 5?

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?