0
0
MongodbHow-ToBeginner · 3 min read

How to Use Explain in MongoDB for Query Analysis

Use the explain() method in MongoDB to get detailed information about how a query is executed. You can call db.collection.find(query).explain() to see the query plan and performance details.
📐

Syntax

The explain() method is called on a query to show how MongoDB executes it. You can use it with find(), aggregate(), or other query methods.

Basic syntax:

  • db.collection.find(query).explain()
  • db.collection.aggregate(pipeline).explain()

You can also specify verbosity levels like "queryPlanner", "executionStats", or "allPlansExecution" to get more detailed output.

mongodb
db.collection.find(query).explain(verbosity)
💻

Example

This example shows how to use explain() with a simple find() query to see the query plan and execution stats.

mongodb
db.users.find({ age: { $gt: 25 } }).explain('executionStats')
Output
{ "queryPlanner": { "plannerVersion": 1, "namespace": "test.users", "indexFilterSet": false, "parsedQuery": { "age": { "$gt": 25 } }, "winningPlan": { "stage": "COLLSCAN", "direction": "forward" }, "rejectedPlans": [] }, "executionStats": { "executionSuccess": true, "nReturned": 3, "executionTimeMillis": 1, "totalKeysExamined": 0, "totalDocsExamined": 5, "executionStages": { "stage": "COLLSCAN", "nReturned": 3, "executionTimeMillisEstimate": 0, "works": 6, "advanced": 3, "needTime": 2, "needYield": 0, "saveState": 0, "restoreState": 0, "isEOF": 1, "direction": "forward", "docsExamined": 5 } }, "serverInfo": { "host": "localhost", "port": 27017, "version": "5.0.0", "gitVersion": "..." }, "ok": 1 }
⚠️

Common Pitfalls

Some common mistakes when using explain() include:

  • Not specifying verbosity and getting less detailed output.
  • Expecting explain() to run the query fully without side effects (some commands may behave differently).
  • Using explain() on write operations incorrectly (it works mainly with read queries).

Always check the verbosity level to get the detail you need.

mongodb
/* Wrong: no verbosity, less info */
db.users.find({ age: { $gt: 25 } }).explain()

/* Right: specify verbosity for detailed stats */
db.users.find({ age: { $gt: 25 } }).explain('executionStats')
📊

Quick Reference

Verbosity LevelDescription
queryPlannerShows the query plan without execution details (default)
executionStatsIncludes query plan plus execution statistics
allPlansExecutionShows all considered query plans and execution stats

Key Takeaways

Use explain() on queries to understand how MongoDB executes them.
Specify verbosity like 'executionStats' to get detailed performance data.
explain() works best with read queries like find() and aggregate().
Check the winning plan to see which index or scan MongoDB uses.
Avoid using explain() on write operations as it may not behave as expected.