LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2517 min read

Compound Indexes

Speed up queries that filter or sort on multiple fields at once using compound indexes, and understand field order.

What Is a Compound Index?

A compound index covers multiple fields in a single index, letting MongoDB efficiently satisfy queries that filter (or sort) across all of them together.

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

Field Order Matters

Unlike a query document, the order of fields in a compound index is significant — it determines how the underlying index is actually structured and which queries it can efficiently serve.

db.orders.createIndex({ customerId: 1, status: 1 });
// Efficiently uses the index:
db.orders.find({ customerId: "u1", status: "shipped" });
db.orders.find({ customerId: "u1" }); // uses just the customerId prefix
// Does NOT efficiently use this index:
db.orders.find({ status: "shipped" }); // skips the first field entirely

The ESR Rule

A widely used heuristic for ordering compound index fields: Equality fields first, then Sort fields, then Range fields.

LetterField TypeExample
EEquality (exact match)customerId: "u1"
SSort.sort({ createdAt: -1 })
RRangetotal: { $gte: 100 }
// Query: find orders for a customer, sorted by date, with total >= 100
db.orders.find({ customerId: "u1", total: { $gte: 100 } }).sort({ createdAt: -1 });
// Following ESR, the ideal compound index is:
db.orders.createIndex({ customerId: 1, createdAt: -1, total: 1 });

The Prefix Property

A compound index on { a: 1, b: 1, c: 1 } can also serve queries on just { a: 1 } or { a: 1, b: 1 } — any leading "prefix" of its fields — but not on { b: 1 } or { c: 1 } alone.

One Well-Designed Index Can Cover Several Queries

Thanks to the prefix property, a single thoughtfully ordered compound index often replaces what would otherwise be several separate single-field indexes.

Common Beginner Mistakes

Creating separate single-field indexes when one compound index would cover all the needed queries

This wastes storage and write overhead — check whether the prefix property already covers your query patterns with fewer indexes.

Ordering fields without considering the ESR rule

A compound index built in the wrong order may not be usable for the actual query shape your app runs, even though the same fields are present.

FAQs

Up to 32 fields, though in practice most useful compound indexes involve just 2-4 fields matched to a specific query pattern.

Yes — different query patterns often warrant different compound indexes, as long as you're deliberate about not over-indexing.

Summary

Compound indexes cover multi-field queries efficiently, with field order (guided by the ESR rule) determining exactly which queries benefit. Next, you'll learn specialized index types for text search and geospatial queries.

Next Lesson →

Text & Geospatial Indexes