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
