liveBook · Manning

Explain()

As explained in MongoDB 8.0 in Action, Third Edition

explain() is a MongoDB method that returns information about how a database operation is planned and executed.

explain() returns information about how MongoDB plans and executes a database operation. Use db.collection.explain() or cursor.explain() to investigate query performance and diagnose inefficient queries. section 7.1.1

Choose a verbosity level based on the evidence needed:

  • queryPlanner, the default, reports the selected query plan. section 7.1.1
  • executionStats adds statistics from executing the query, including returned documents, execution time, and examined keys and documents. section 7.1.1
  • allPlansExecution reports all considered plans and their execution statistics; true is accepted for compatibility and means this mode. section 7.1.1

Inspecting an indexed query

Run db.collection.find({ yourField: "value" }).explain("executionStats"). Read the winningPlan tree from the lower stages upward: IXSCAN finds matching index keys, FETCH retrieves the documents, and the top stage produces the results. Compare nReturned, executionTimeMillis, totalKeysExamined, and totalDocsExamined to assess efficiency. section 7.1.1

Listing 7.1 Appending the MongoDB explain () method
db.collection.find(
    { yourField: "value" }
).explain() // Explain the default query planner information

db.collection.find(
    { yourField: "value" }
).explain(
    "executionStats" // Explain the query execution statistics
)

db.collection.find(
    { yourField: "value" }
).explain(
    "allPlansExecution" // Explain the query execution
➥plan with all possible query plans
)

Compare copyable explain() calls using the default planner view, execution statistics, and all-plan execution details. section 7.1.1

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Descends from verbosity choices to execution-plan stages and runtime metrics, while leaving query-engine selection automatic.
Examples
Uses mongosh find() queries, IXSCAN and FETCH stages, winningPlan output, and execution-statistics fields.
What it assumes
Uses MongoDB collection queries and indexes while defining plan stages and verbosity modes explicitly.
What you can do after
Diagnose/debug with it by comparing winning plans, execution stages, examined data, and query timing.
How it connects
Connects query planners, indexes, execution plans, execution statistics, and query engines.

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.