liveBook · Manning

totalKeysExamined

As explained in MongoDB 8.0 in Action, Third Edition

totalKeysExamined is an explain-plan metric reporting the number of index keys examined while executing a MongoDB operation.

totalKeysExamined reports how many index keys MongoDB examined while executing an operation. Read it in explain("executionStats") output alongside nReturned, executionTimeMillis, and totalDocsExamined to assess whether an index limits unnecessary scanning. section 7.1.1

Interpret the metric with the winning execution stage:

  • An IXSCAN plan examines index keys; when totalKeysExamined and totalDocsExamined are both 1 for one returned document, the indexed lookup is selective. section 7.1.1
  • A COLLSCAN can report totalKeysExamined: 0 because MongoDB scans documents rather than index keys; totalDocsExamined can still be large. section 7.2.2
  • A high key count relative to returned results indicates that the query examined many index entries before producing its result set. section 7.1.1

Inspect an indexed query

Run db.collection.find({ yourField: "value" }).explain("executionStats"). The sample plan uses the yourField_1 index, returns one document, examines one index key and one document, and completes in 3 ms. For a compound-index query, compare the same metrics after applying an index whose field order follows the query’s equality, sort, and range needs. section 7.2.2

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines the metric and interprets IXSCAN and COLLSCAN results, but does not detail its internal calculation.
Examples
Uses a one-document IXSCAN example and a 3,472-result COLLSCAN that examines 21,349 documents and zero index keys.
What it assumes
Assumes familiarity with MongoDB queries and indexes while demonstrating explain modes and execution-plan stages.
What you can do after
Diagnose query efficiency with explain("executionStats") by comparing examined keys and documents with returned results.
How it connects
Connects totalKeysExamined to explain plans, executionStats, IXSCAN, FETCH, COLLSCAN, compound indexes, and the ESR rule.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.