⬅ Previous Topic
Multikey Indexes for ArraysNext Topic ⮕
Introduction to Aggregation⬅ Previous Topic
Multikey Indexes for ArraysNext Topic ⮕
Introduction to AggregationMongoDB provides the explain()
method to help developers analyze how queries are executed internally. This is essential when optimizing slow queries or verifying whether indexes are being used effectively.
explain()
shows the execution plan of a query — how MongoDB selects documents, whether it uses indexes or performs a full collection scan, and how many documents are scanned or returned.
It helps you answer key questions like:
You can append .explain()
to any query or cursor. MongoDB will then return metadata about the query's execution plan.
db.collection.find({ field: value }).explain()
db.users.insertMany([
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 },
{ name: "David", age: 25 },
{ name: "Eve", age: 40 }
]);
Now query for users aged 25 without any index:
db.users.find({ age: 25 }).explain("executionStats")
Output:
{ ... "executionStats": { "totalDocsExamined": 5, "totalKeysExamined": 0, "executionStages": { "stage": "COLLSCAN", ... } } ... }
Explanation: The output shows stage: "COLLSCAN"
which means the query did a collection scan — it examined all 5 documents to find matches. This is inefficient for large datasets.
Q: What does it mean if "stage": "COLLSCAN"
appears in your explain output?
A: MongoDB is scanning the entire collection because it doesn’t have an index on the field you're querying.
db.users.createIndex({ age: 1 })
Output:
{ "createdCollectionAutomatically": false, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 }
db.users.find({ age: 25 }).explain("executionStats")
Output:
{ ... "executionStats": { "totalDocsExamined": 2, "totalKeysExamined": 2, "executionStages": { "stage": "IXSCAN", ... } } ... }
Explanation: Now the query uses stage: "IXSCAN"
— index scan. MongoDB only examined the 2 documents matching age = 25. Much faster and efficient!
Here are a few key fields to look at in explain("executionStats")
output:
Q: Should totalDocsExamined always equal nReturned?
A: No. If there’s a filter, MongoDB may examine more documents than it returns.
If you want MongoDB to use a specific index or test index behavior, you can use .hint()
:
db.users.find({ age: 25 }).hint({ age: 1 }).explain("executionStats")
The explain()
method is your window into MongoDB's query planner. It helps you:
Using explain("executionStats")
is an essential habit when optimizing MongoDB queries for performance, especially at scale.
⬅ Previous Topic
Multikey Indexes for ArraysNext Topic ⮕
Introduction to AggregationYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.