Q16: Explain the ESR (Equality, Sort, Range) Rule for compound indexes.

The ESR Rule guides optimal compound index field placement:

  1. E (Equality): Put fields matched on exact values first (status: 'active').
  2. S (Sort): Put fields used for ordering second (createdAt: -1).
  3. 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 (SORT stage 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?