How to Check If Index Is Being Used in MongoDB
Use the
explain() method on your MongoDB query to check if an index is being used. The output shows whether the query used an index scan or a collection scan, indicating index usage.Syntax
The explain() method is called on a query to get details about how MongoDB executes it. The key parts are:
db.collection.find(query).explain(): Runs the query with explain to show execution details.executionStats: Mode to get detailed stats including index usage.queryPlanner: Shows the plan MongoDB chose, including index info.
mongodb
db.collection.find({ field: value }).explain('executionStats')Example
This example shows how to check if an index is used for a query on the users collection filtering by age.
mongodb
db.users.createIndex({ age: 1 })
db.users.find({ age: 30 }).explain('executionStats')Output
{
"queryPlanner": {
"winningPlan": {
"stage": "IXSCAN",
"keyPattern": { "age": 1 },
"indexName": "age_1"
}
},
"executionStats": {
"totalKeysExamined": 5,
"totalDocsExamined": 5
}
}
Common Pitfalls
Common mistakes when checking index usage include:
- Not using
explain('executionStats')which gives detailed info; default explain may be too brief. - Confusing
COLLSCAN(collection scan) withIXSCAN(index scan); onlyIXSCANmeans index is used. - Forgetting to create the index before testing.
mongodb
/* Wrong: No explain, no index info */ db.users.find({ age: 30 }) /* Right: Use explain with executionStats */ db.users.find({ age: 30 }).explain('executionStats')
Quick Reference
Summary tips to check index usage:
- Use
explain('executionStats')on your query. - Look for
IXSCANinwinningPlan.stageto confirm index use. - If you see
COLLSCAN, no index was used. - Check
indexNameto know which index was used.
Key Takeaways
Use the explain() method with 'executionStats' to see if an index is used.
Look for 'IXSCAN' in the query plan to confirm index usage.
A 'COLLSCAN' means MongoDB did not use an index for the query.
Always create the index before testing its usage.
Check the 'indexName' field to identify which index was used.