Q16: Explain the ESR (Equality, Sort, Range) Rule for compound indexes.
The ESR Rule guides optimal compound index field placement:
- E (Equality): Put fields matched on exact values first (
status: 'active'). - S (Sort): Put fields used for ordering second (
createdAt: -1). - R (Range): Put fields filtered by inequality ranges last (
age: { $gt: 21 }).
Key Takeaways
Equality fields $ o$ Sort fields $ o$ Range fields.
Prevents in-memory sorting operations (
SORTstage in explain execution).
Knowledge Check
Applying the ESR rule to find({ status: 'A', age: { $gt: 20 } }).sort({ name: 1 }), what is the optimal compound index order?