LESSON 07 / 20·2 min readIntermediate

What is the ESR rule?

01 Understand02 Recall03 Prepare

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 by createdAt, 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:

JavaScript
db.orders.createIndex({ status: 1, createdAt: -1 });
db.orders.find({ status: 'paid' }).sort({ createdAt: -1 }).limit(20);
  • status is the equality field and createdAt supports the requested order. Confirm the plan for the actual dataset. MongoDB ESR guidance.
PAUSE & RECALL

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.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Explain why the field order serves a specific filter-and-sort query, then verify with execution statistics.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: What should I check in explain?

Adapted from 04_MONGODB_MONGOOSE.md · “What is the ESR rule?”. Examples are study fragments; framework behavior can depend on your version.