All academies
Roadmap
LEVEL 6 · INDEXES

Compound Indexes & ESR

12 min read

A compound index covers multiple fields: { category: 1, price: -1 }. Order is critical — the index supports queries on a prefix of its fields: category alone works, price alone does not.

The ESR rule

Order compound index fields as: Equality first, Sort second, Range last. For find({ status: "active", age: { $gt: 21 } }).sort({ created: -1 }) the ideal index is { status: 1, created: -1, age: 1 }.

Covered queries

If the index contains every field the query filters on and returns, MongoDB never touches the documents at all — the fastest possible read.

mongosh
db.users.createIndex({ email: 1, name: 1 })
// covered: filter + projection both within the index
db.users.find({ email: "a@b.com" }, { name: 1, _id: 0 })

Other index types

Multikey (automatic for arrays), text for full-text search, 2dsphere for geospatial, TTL to auto-expire documents, partial to index a subset, hashed for sharding.

Try it yourself

db.products.createIndex({ category: 1, price: -1 })
Run in Shell

Check your understanding

Q1.

Index: { a: 1, b: 1, c: 1 }. Which query CANNOT use it?

Q2.

Per the ESR rule, fields in a compound index should be ordered:

Q3.

A covered query never needs to read the actual documents.