Optimizing Query Performance

1. Analyzing Query Performance

ToolDetail
explain()Plan analysis
profilerCaptures slow ops
Atlas Performance AdvisorIndex suggestions

2. Understanding Explain Plans

ModeDetail
queryPlannerChosen + rejected plans
executionStatsnReturned, totalKeysExamined, totalDocsExamined
allPlansExecutionStats for all candidate plans

3. Using Covered Queries

ConditionDetail
ProjectionOnly indexed fields, exclude _id
PredicateAll filter fields in index
EffecttotalDocsExamined = 0

4. Avoiding Collection Scans

SymptomFix
stage = COLLSCANAdd supporting index
Regex w/o anchorUse prefix anchor or text index

5. Optimizing Index Selection

AspectDetail
ESR ruleEquality → Sort → Range field order
hint()Force index when planner chooses poorly

6. Using Index Intersection

AspectDetail
MechanismCombines bounds from two indexes
CaveatUsually slower than a well-chosen compound index

7. Understanding Query Selectivity

AspectDetail
SelectiveReturns small fraction → index efficient
Non-selectiveReturns most docs → scan may be faster

8. Optimizing Sort Operations

FormDetail
Indexed sortStage SORT absent in explain
Blocking SORTLimited by 100MB (use allowDiskUse)

9. Using Projection to Reduce Data

BenefitDetail
NetworkLess bytes transferred
Covered queryEnables index-only execution

10. Implementing Query Caching Strategies

LayerDetail
Plan cacheReuses query plans (clearable)
App cacheRedis / in-process for hot reads
Materialized views$merge into pre-aggregated collection

11. Understanding Query Targeting

ClusterDetail
TargetedShard key in filter → single shard
BroadcastScatter-gather to all shards
TipInclude shard key whenever possible