Index Management
Create Index
db.collection.createIndex(
{"field": 1},
{
background: true,
name: "custom_index_name",
unique: false
}
)
Get Indexes
db.collection.getIndexes()
View Index Size
db.collection.totalIndexSize()
Delete Index
db.collection.dropIndex("INDEX-NAME")
explain Analysis
Three Modes
- queryPlanner mode (default): Returns the winning plan selected by query optimizer
- executionStats mode: Provides actual execution statistics
- allPlansExecution mode: Most detailed execution plan analysis
executionStats Core Metrics
executionTimeMillis
- Complete execution time for the entire query statement
Document and Index Scan Counts
- nReturned: Actual number of documents returned by query
- totalKeysExamined: Number of index entries scanned
- totalDocsExamined: Number of complete documents scanned
Ideal state: nReturned = totalKeysExamined = totalDocsExamined
Stage Status Analysis
Stages you want to see:
- IDHACK: Direct query using _id field
- IXSCAN: Index scan
- FETCH: Retrieves complete documents based on index pointers
Stages you don’t want to see:
- COLLSCAN: Full table scan
- SORT: In-memory sort without using index
Performance Optimization Suggestions
- Create appropriate indexes for query conditions
- Compound indexes must follow leftmost prefix principle
- Use covered queries to avoid fetching documents
- Ensure sort fields have indexes established