Bussola

Reading MongoDB explain() in Five Minutes: COLLSCAN vs IXSCAN

To read a MongoDB explain COLLSCAN result, run the query with explain("executionStats") and compare two numbers: totalDocsExamined and nReturned. A COLLSCAN stage means the server read every document in the collection; an IXSCAN stage means it walked an index. If totalDocsExamined is far larger than nReturned, the query does more work than it needs to, and an index (or a better index) is usually the fix. The rest of this article shows where to find those fields, what each stage means, and how to design a compound index with the ESR rule.

Getting the right explain output

explain() has three verbosity modes:

db.orders.find({ status: "shipped" }).explain("queryPlanner")
db.orders.find({ status: "shipped" }).explain("executionStats")
db.orders.find({ status: "shipped" }).explain("allPlansExecution")
  • queryPlanner (the default) shows the winning plan without running the query. Good for checking which index would be chosen, useless for measuring cost.
  • executionStats runs the query to completion and reports what actually happened. This is the mode you want most of the time.
  • allPlansExecution also reports the trial results of the candidate plans that lost. Use it when you wonder why the planner did not pick the index you expected.

Note that executionStats really executes the query. For reads that is fine; for a very slow query on a busy primary, think before running it. Explaining an update or delete does not apply the change, but it still does the matching work.

You can also explain aggregations with db.orders.explain("executionStats").aggregate([...]).

The fields that matter

The output is a large document. Ignore most of it and look at these:

executionStats: {
  nReturned: 120,
  executionTimeMillis: 480,
  totalKeysExamined: 0,
  totalDocsExamined: 250000,
  executionStages: { stage: "COLLSCAN", ... }
}
queryPlanner.winningPlan: { stage: "COLLSCAN", ... }
Field Meaning
nReturned Documents the query returned
totalKeysExamined Index entries scanned
totalDocsExamined Documents loaded from the collection
executionTimeMillis Total time spent executing
winningPlan The plan tree the planner chose

The ratio that tells you the most is totalDocsExamined / nReturned. A well-indexed query is close to 1:1. A ratio of roughly 2,000:1, as in the example above, says the server read 250,000 documents to return 120.

Also watch totalKeysExamined. An index scan can still be wasteful: if keys examined is much larger than nReturned, the index is only partly selective and the server is scanning many entries to find few matches.

The stages you will see

The plan is a tree; read it from the innermost inputStage outward.

  • COLLSCAN: a full collection scan. Fine for tiny collections, a problem for large ones.
  • IXSCAN: a scan over an index range. Check indexName, indexBounds and direction. Tight bounds like ["shipped", "shipped"] are good; bounds like [MinKey, MaxKey] mean the index is not narrowing anything.
  • FETCH: loads the full document using the location found in the index. IXSCAN followed by FETCH is the normal case.
  • PROJECTION_COVERED: the query was answered from the index alone, so no documents were fetched and totalDocsExamined is 0. This requires every filtered and returned field to be in the index, and _id excluded from the projection unless it is in the index.
  • SORT: the server sorted results in memory because no index provided the order. When an index already delivers the order, no SORT stage appears. In-memory sorts have a memory limit; beyond it the query fails unless disk use is allowed, and the exact limit and behavior vary by server version.
  • LIMIT, SKIP: applied after the stage below them. A large skip still examines all the skipped entries.

Worked example: before and after

Suppose orders has 250,000 documents and you run:

db.orders.find({ status: "shipped", customerId: 4812 })
         .sort({ createdAt: -1 })
         .limit(20)
         .explain("executionStats")

Without a useful index, the plan looks roughly like this (trimmed):

winningPlan: {
  stage: "SORT",
  sortPattern: { createdAt: -1 },
  limitAmount: 20,
  inputStage: { stage: "COLLSCAN", filter: { ... } }
}
executionStats: { nReturned: 20, totalKeysExamined: 0, totalDocsExamined: 250000 }

Two problems: a COLLSCAN and an in-memory SORT. Now create a compound index:

db.orders.createIndex({ customerId: 1, status: 1, createdAt: -1 })

Run the same query again:

winningPlan: {
  stage: "LIMIT",
  inputStage: {
    stage: "FETCH",
    inputStage: {
      stage: "IXSCAN",
      indexName: "customerId_1_status_1_createdAt_-1",
      indexBounds: {
        customerId: ["[4812, 4812]"],
        status: ["[\"shipped\", \"shipped\"]"],
        createdAt: ["[MaxKey, MinKey]"]
      }
    }
  }
}
executionStats: { nReturned: 20, totalKeysExamined: 20, totalDocsExamined: 20 }

The SORT stage is gone because the index already holds the entries in createdAt descending order within each customerId and status pair. The server reads 20 index entries and 20 documents instead of 250,000. The numbers and the exact plan shape will differ on your data and server version, but the improvement pattern is typical.

Choosing index field order: the ESR rule

For compound indexes, a widely used guideline is Equality, Sort, Range:

  1. Equality fields first: those matched with an exact value (status: "shipped", or $in with a few values).
  2. Sort fields next, in the same direction pattern as the query sort.
  3. Range fields last: $gt, $gte, $lt, $lte, $ne, and similar.

Why: a range on an early field splits the index into many ranges, and the sort order across those ranges is lost, forcing an in-memory SORT. Putting the sort field before the range field keeps the results ordered.

Example: filter on status (equality), sort by createdAt, and restrict total to a range:

db.orders.find({ status: "shipped", total: { $gt: 50 } }).sort({ createdAt: -1 })

// ESR: equality (status), sort (createdAt), range (total)
db.orders.createIndex({ status: 1, createdAt: -1, total: 1 })

ESR is a guideline, not a law. If the range is highly selective (it eliminates most documents) and the result set is small, putting the range before the sort and accepting an in-memory sort of a few documents can be cheaper. Measure with executionStats rather than assuming.

Common reasons an index is not used

  • The query shape does not match the index prefix. A compound index on { a: 1, b: 1 } supports queries on a and on a, b, but not on b alone.
  • Type mismatch. Querying { customerId: "4812" } when the field stores numbers matches nothing, and the index will not help. See why Int64 values change in JavaScript for a related type trap.
  • Unanchored or case-insensitive regex. { name: /smith/ } cannot use tight index bounds. Anchoring with ^ helps for case-sensitive patterns.
  • Low selectivity. If a filter matches most of the collection, scanning the collection can be as fast as the index and the planner may choose accordingly.
  • A surprising plan. Use allPlansExecution, or .hint("indexName") as a test, to compare candidates directly.

To see which indexes exist, run db.orders.getIndexes(). To find indexes that are never used, db.orders.aggregate([{ $indexStats: {} }]) reports usage counters per index since the last server restart. Each index costs write throughput and storage, so do not add one per query.

A quick checklist

  1. Run explain("executionStats"), not the default mode.
  2. Compare totalDocsExamined and totalKeysExamined to nReturned.
  3. Look for COLLSCAN on large collections and for SORT stages.
  4. Build a compound index with equality fields first, then sort, then range.
  5. Re-run explain and confirm the stage, the bounds and the counters changed.
  6. Check the write cost and remove indexes nobody uses.

When you are away from a laptop, the on-call checklist covers currentOp and missing-index checks, and a mobile client such as Bussola lets you run filters and aggregations against a deployment. Index management is not available in the app yet, so run createIndex from mongosh or Atlas.

mongodbexplainindexesperformancemongosh

Bussola is a free MongoDB client for iPhone: query, edit and aggregate over a direct connection, with no backend.

Coming soon to the App Store