Index Analysis and Optimization
Analyze query performance with explain plans, identify missing indexes, and optimize existing indexes to speed up MongoDB queries.
Prerequisites
- -MongoDB 6+ with mongosh
- -A database with collections and data to analyze
Steps
Analyze a query with explain
Run explain on a query to see if it uses an index or performs a full collection scan.
Look for COLLSCAN in the winning plan. That means no index is being used and the query scans every document.
List all indexes on a collection
View existing indexes and their key patterns to understand current coverage.
Create a compound index for a common query
Add an index that covers frequently queried field combinations.
Order index fields by equality filters first, then sort fields, then range filters (ESR rule).
Find unused indexes
Identify indexes that consume storage but are never used by any query.
Index stats reset on server restart. Check over a full business cycle (at least a week) before dropping unused indexes.
Check index sizes
View how much memory each index consumes to prioritize optimization.
Full Script
FAQ
Discussion
Loading comments...