Index performance is critical for maintaining efficient database operations. This section explores strategies to optimize MongoDB index performance.
1. Query Explain Analysis
Use explain()
to understand query execution and index usage.
## Analyze query performance
db.users.find({"age": 30}).explain("executionStats")
Explain Output Metrics
Metric |
Description |
nReturned |
Number of documents returned |
totalDocsExamined |
Total documents scanned |
indexesUsed |
Indexes utilized in query |
2. Selective Indexing
Partial Indexes
Create indexes for specific document subsets.
## Create a partial index for active users
db.users.createIndex(
{"email": 1},
{"partialFilterExpression": {"status": "active"}}
)
3. Index Intersection
MongoDB can combine multiple indexes for complex queries.
## Create indexes for potential intersection
db.products.createIndex({"category": 1})
db.products.createIndex({"price": 1})
4. Covered Queries
Optimize queries that can be satisfied entirely by indexes.
## Create a covering index
db.users.createIndex({"username": 1, "email": 1})
graph TD
A[Query Performance Analysis] --> B{Index Exists?}
B --> |No| C[Create Appropriate Index]
B --> |Yes| D[Analyze Index Efficiency]
D --> E[Use explain()]
E --> F{Optimal Performance?}
F --> |No| G[Modify/Redesign Index]
F --> |Yes| H[Monitor Continuously]
5. Index Cardinality
High Cardinality Fields
Prefer indexing fields with many unique values.
## Good index candidate
db.users.createIndex({"unique_identifier": 1})
Low Cardinality Fields
Less effective for indexing.
6. Compound Index Optimization
Order fields strategically in compound indexes.
## Effective compound index
db.orders.createIndex({"status": 1, "created_at": -1})
7. Regular Maintenance
Index Rebuilding
## Rebuild index
db.users.reIndex()
Tool |
Purpose |
MongoDB Compass |
Visual performance analysis |
mongostat |
Real-time server statistics |
mongotop |
Time spent reading/writing |
Best Practices
- Create indexes based on query patterns
- Avoid over-indexing
- Use
explain()
frequently
- Monitor index usage
- Regularly review and update indexes
- Indexing rarely used fields
- Creating too many indexes
- Ignoring write performance impact
- Not monitoring index usage
LabEx recommends a systematic approach to index optimization, focusing on actual query patterns and continuous performance monitoring.