Working with Compound Indexes

1. Creating Compound Index

FormEffect
createIndex({a:1, b:-1})Two-key index
Max keys32 fields per compound index

2. Understanding Index Order

PrincipleEffect
Equality firstMost-selective equality fields first
Sort nextThen sort fields in sort order
Range lastRange/inequality fields last
Rule"ESR" rule: Equality, Sort, Range

3. Using Prefix Queries

IndexSupported queries
{a:1, b:1, c:1}{a}, {a,b}, {a,b,c}
Not supported{b} alone, {c} alone, {b,c}

4. Understanding Sort Direction Optimization

IndexCompatible sort
{a:1, b:-1}sort({a:1,b:-1}) or sort({a:-1,b:1})
Not compatiblesort({a:1,b:1})
ReasonIndex can be scanned forward or backward, not mixed per key

5. Optimizing Compound Index for Queries

GoalStrategy
Single index per query patternDesign index matching query+sort exactly
Avoid duplicatesCompound {a,b} covers {a}; don't add separate {a}
SelectivityMost selective field early reduces scanned keys

6. Setting Index Options

OptionEffect
uniqueEnforce uniqueness on combination
partialFilterExpressionIndex subset of docs
collationString comparison rules
hiddenHide from planner (test impact)
nameCustom name

7. Understanding Covered Queries

RequirementDetail
All query fields indexedFilter only uses indexed fields
All projected fields indexedNo fetch from collection
_id excludedUnless _id is in index
No arrays in indexMultikey indexes can't cover
Indicatorexplain shows totalDocsExamined: 0

8. Analyzing Compound Index Performance

Metric (explain)Goal
totalKeysExaminedClose to nReturned
totalDocsExamined0 (covered) or close to nReturned
stageIXSCAN (not COLLSCAN)
SORT_KEY_GENERATORAbsent = index-supported sort

9. Using Compound Index for Sorting

PatternIndex
Filter status, sort by date{status:1, createdAt:-1}
Range + sort same key{createdAt:-1}

10. Avoiding Index Intersection

IssueSolution
Two single indexes intersectedSlower than one compound
FixCreate compound {a:1, b:1} for common queries
DropRemove redundant single-field indexes