17. Reading explain() and Query Plans
explain() reveals how MongoDB plans and executes a query. Common modes include query-planning information and execution statistics. For performance investigations, executionStats is often useful because it reports work performed by the selected plan.
Important fields and concepts include the winning plan, index scan stages, collection scan stages, keys examined, documents examined, and documents returned. The exact output structure varies by version and execution engine.
A useful starting point is to compare the number of documents examined with the number returned. A large difference can indicate that a query examines many candidates, although the interpretation depends on the operation and plan. A collection scan is not automatically bad for a tiny collection or a query that returns most documents.
Do not rely on one metric in isolation. Check latency under realistic load, index usage, sort behavior, and resource utilization.
db.orders.find({ status: "delivered" })
.sort({ createdAt: -1 })
.limit(20)
.explain("executionStats");- Explain output shows the chosen query plan and execution details.
- Inspect keys examined, documents examined, and documents returned.
- A collection scan is not always a problem.
- Combine explain analysis with realistic latency measurements.
Which explain mode provides execution statistics for the selected plan?