What is the ESR rule?
Understand the concept
ESR stands for Equality, Sort and Range, a common starting point for ordering fields in a compound index. Equality fields narrow the relevant index region, sort fields can let MongoDB read in the desired order, and range fields constrain intervals. It is a guideline that must be checked against selectivity and the query plan.
Important ideas
-
Equality → Sort → Range is a starting point for compound index order.
-
Example: filter by
status, sort bycreatedAt, then apply a range field. -
Confirm with
explain; highly selective range filters may justify another order. -
A compound index is ordered, so a query that skips leading fields may use it less effectively.
Example — Mongo shell:
db.orders.createIndex({ status: 1, createdAt: -1 });
db.orders.find({ status: 'paid' }).sort({ createdAt: -1 }).limit(20);statusis the equality field andcreatedAtsupports the requested order. Confirm the plan for the actual dataset. MongoDB ESR guidance.
Can you explain it without the notes?
What is the ESR rule?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
ESR stands for Equality, Sort and Range, a common starting point for ordering fields in a compound index. Equality fields narrow the relevant index region, sort fields can let MongoDB read in the desired order, and range fields constrain intervals. It is a guideline that must be checked against selectivity and the query plan.
Turn this concept into a clear answer.
- Explain why the field order serves a specific filter-and-sort query, then verify with execution statistics.
Adapted from 04_MONGODB_MONGOOSE.md · “What is the ESR rule?”. Examples are study fragments; framework behavior can depend on your version.