Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Display MongoDB explain query plan?
To analyze MongoDB query performance and execution strategy, use the explain() method. This provides detailed information about how MongoDB processes your queries, including execution stages, index usage, and performance metrics.
Syntax
db.collection.find(query).explain();
db.collection.find(query).explain("executionStats");
db.collection.find(query).explain("allPlansExecution");
Sample Data
db.demo202.insertMany([
{"StudentFirstName": "Chris", "StudentAge": 21},
{"StudentFirstName": "David", "StudentAge": 23},
{"StudentFirstName": "Bob", "StudentAge": 22}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3c3bd103d395bdc21346e8"),
ObjectId("5e3c3bd803d395bdc21346e9"),
ObjectId("5e3c3bde03d395bdc21346ea")
]
}
Example: Basic Query Plan
db.demo202.find({"StudentFirstName": "David"}).explain();
{
"queryPlanner": {
"plannerVersion": 1,
"namespace": "test.demo202",
"indexFilterSet": false,
"parsedQuery": {
"StudentFirstName": {
"$eq": "David"
}
},
"winningPlan": {
"stage": "COLLSCAN",
"filter": {
"StudentFirstName": {
"$eq": "David"
}
},
"direction": "forward"
},
"rejectedPlans": []
},
"ok": 1
}
Key Points
- COLLSCAN indicates a collection scan (no index used)
- IXSCAN would indicate index usage for better performance
-
winningPlanshows the execution strategy MongoDB selected - Use
explain("executionStats")for detailed performance metrics
Conclusion
The explain() method is essential for query optimization in MongoDB. It reveals execution stages, helping identify when indexes are needed to improve query performance from collection scans to efficient index scans.
Advertisements
