explain() reveals the execution plan MongoDB chose for a query — which index was used, how many documents and index keys were examined, and how long the query took. It is the primary tool for verifying index effectiveness and diagnosing slow queries.
// Attach .explain() to any find(), aggregate(), or cursor operation db.users.find({ email: "user@example.com" }).explain() db.users.find({ email: "user@example.com" }).explain("executionStats") db.users.find({ email: "user@example.com" }).explain("allPlansExecution") // For aggregation pipelines db.orders.aggregate( [ { $match: { status: "active" } }, { $group: { _id: "$region", total: { $sum: "$amount" } } } ], { explain: true } ) // Cursor method form (equivalent) db.users.explain("executionStats").find({ email: "user@example.com" })
What explain() Returns
The output is a JSON document with three main sections:
- queryPlanner: the plan chosen by the optimizer, without running the query
- executionStats: actual runtime numbers — only present with
"executionStats"or higher verbosity - serverInfo: MongoDB version, host, and port
explain() without arguments uses "queryPlanner" verbosity by default — it shows the chosen plan but does not execute the query. To see actual documents examined and timing, you must use "executionStats". For performance diagnosis, always use "executionStats".