explain() (Explain Execution Plan)
Last updated: 2026-10-09
explain() (Explain Execution Plan)
explain() reveals a query's execution plan: `db.users.find({ age: { $gt: 20 } }).explain('executionStats')`. The result shows index usage, scanned documents, and timing — the core toolkit for performance tuning. The argument can be 'queryPlanner' (default, plan only), 'executionStats' (actual execution stats), or 'allPlansExecution' (every candidate plan).
| Category | Cursor |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.find(<filter>).explain(<verbosity>)
⚙️ Parameters
| mode | Optional. 'queryPlanner', 'executionStats', or 'allPlansExecution'. |
|---|
Returns:Document with the execution plan and stats.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// explain: check whether the age query uses an index
const plan = db.users.find({ age: { $gt: 20 } })
.explain('executionStats')
print('Docs examined: ' + plan.executionStats.totalDocsExamined)
Output:
Docs examined: 1000
📌 Notes
- totalDocsExamined far above the result count signals a missing index
- winningPlan shows the real plan the optimizer settled on
- explain() returns plan info, not actual data
🏷️ Related Tags
💡 Related Cases
Indexing Fundamentals and Principles
Index Types and Advanced Features
$lookup and Associations with Multiple Sets
Performance Optimization and Monitoring: Production-Level Tuning
Sharding: Horizontal Scaling
📚 Related Tutorials
❓ FAQ
QHow do I tell whether a query uses an index?
AInspect winningPlan: IXSCAN means an index was used, COLLSCAN means a full collection scan.
QWhat are the differences among explain's three modes?
AqueryPlanner shows the plan only and is fastest; executionStats adds actual execution stats; allPlansExecution details every candidate plan.
QDoes explain actually run the query?
AIt does execute (except in queryPlanner mode) — stats come from a real run, but no documents are returned.