Skip to content

Lesson 5 of 9 · 23m

Compound Indexes and the ESR Rule

Equality, sort, then range — the practical ordering rule behind most compound indexes, with the exceptions that scar tissue teaches.

Most MongoDB indexing mistakes are not exotic. They are compound indexes with fields in the wrong order. The practical starting point is ESR: equality fields first, sort fields next, range fields last. It works because of how compound B-tree bounds narrow the search space.

Why order matters

Imagine this query:

db.orders.find({
  tenantId: t,
  status: "paid",
  createdAt: { $gte: start, $lt: end }
}).sort({ createdAt: -1 })

The index that serves it cleanly is:

db.orders.createIndex({ tenantId: 1, status: 1, createdAt: -1 })

MongoDB can seek to one tenant, one status, then walk the createdAt range in exactly the order requested. Put createdAt before status and the index becomes a range scan across many statuses followed by filtering. Same fields, different physics.

Prefixes are the compound index contract

An index on { a: 1, b: 1, c: 1 } supports predicates using a, a+b, or a+b+c. It does not efficiently support a query only on b or c. This is the leftmost-prefix rule. A separate index on { b: 1 } may still be justified, but do not duplicate an index whose usage is already covered by a compound prefix.

Sorting is part of the query shape

These are different queries operationally:

.find({ tenantId: t }).sort({ createdAt: -1 })
.find({ tenantId: t, status: "paid" }).sort({ createdAt: -1 })
.find({ tenantId: t }).sort({ status: 1, createdAt: -1 })

A good index makes the requested order fall out of the index traversal. If equality occupies the fields before the sort field, sorted output can be produced without a blocking in-memory sort. Mixed ascending and descending directions matter too: { a: 1, b: -1 } is not equivalent to { a: 1, b: 1 } for multi-field sorts.

Covered queries are the fast lane

If the index contains every field the query needs, MongoDB can answer from index keys alone:

db.orders.createIndex({ tenantId: 1, status: 1, createdAt: -1, orderNumber: 1 })
db.orders.find(
  { tenantId: t, status: "paid" },
  { _id: 0, orderNumber: 1, createdAt: 1 }
)

A true covered query shows totalDocsExamined: 0 and a PROJECTION_COVERED stage. Do not contort every query into one, but hot read paths benefit enormously.

Field notes

  • ESR is a heuristic, not scripture. Highly selective ranges sometimes deserve earlier placement; verify with explain.
  • Multikey indexes on arrays cannot support every compound combination. A compound multikey index can contain at most one array field.
  • Index intersection exists, but relying on it is usually a sign the real compound index is missing.
  • Review index usage periodically with $indexStats; unused indexes are write tax, memory pressure, and migration noise.

Was this lesson helpful?

Sign in to rate