Explain plan analysis helps you understand how MongoDB runs your query. It shows the steps MongoDB takes to find your data and how long it takes.
0
0
Explain plan analysis (queryPlanner, executionStats) in MongoDB
Introduction
You want to see if your query is using indexes to be faster.
You need to find why a query is slow and how to improve it.
You want to check how many documents MongoDB scans to answer your query.
You want to compare different query methods to pick the best one.
Syntax
MongoDB
db.collection.find(query).explain('executionStats')queryPlanner shows the plan MongoDB chooses to run your query.
executionStats adds details about how many documents were scanned and how long it took.
Examples
Shows the query plan without execution details.
MongoDB
db.users.find({ age: { $gt: 25 } }).explain('queryPlanner')Shows the query plan plus how many documents were scanned and time taken.
MongoDB
db.users.find({ age: { $gt: 25 } }).explain('executionStats')Defaults to
queryPlanner mode if no argument is given.MongoDB
db.users.find({ name: 'Alice' }).explain()Sample Program
This inserts three users, then runs a query to find users older than 25. It shows the query plan and execution stats.
MongoDB
db.users.insertMany([
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 20 },
{ name: 'Carol', age: 35 }
])
const result = db.users.find({ age: { $gt: 25 } }).explain('executionStats')
printjson(result)OutputSuccess
Important Notes
If your query does not use an index, MongoDB will do a collection scan (COLLSCAN), which is slower.
Look at totalDocsExamined vs nReturned to see efficiency.
Use explain('executionStats') to get detailed timing and document counts.
Summary
Explain plan shows how MongoDB runs your query step-by-step.
Use queryPlanner to see the plan chosen.
Use executionStats to see how many documents were scanned and how long it took.