explain()
explain shows how MongoDB executes a query: which index it used and how many documents it examined.
In this page:
Syntax
db.collection_name.find(filter).explain("executionStats")
explain()
Call .explain("executionStats") on a cursor. Look at winningPlan for IXSCAN (index scan) versus COLLSCAN (full scan), and compare totalDocsExamined with nReturned.
A large gap means the query is inefficient. hint() forces a particular index for testing.
Note:
Aim for totalDocsExamined close to nReturned.
Example: explain()
test> db.users.find({ email: "[email protected]" }).explain("executionStats").executionStats
{
nReturned: 1,
totalKeysExamined: 1,
totalDocsExamined: 1,
executionStages: { stage: 'FETCH', inputStage: { stage: 'IXSCAN', indexName: 'email_1' } }
}
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Ignoring COLLSCAN in plans
- Trusting timing on tiny data
- Not comparing docs examined with returned
Chapter Summary
- explain shows the query plan
- IXSCAN uses an index, COLLSCAN does not
- Compare docs examined and returned
- hint forces an index
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: