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 entirelyThe ESR Rule
A widely used heuristic for ordering compound index fields: Equality fields first, then Sort fields, then Range fields.
| Letter | Field Type | Example |
|---|---|---|
| E | Equality (exact match) | customerId: "u1" |
| S | Sort | .sort({ createdAt: -1 }) |
| R | Range | total: { $gte: 100 } |
// Query: find orders for a customer, sorted by date, with total >= 100db.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.
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
This wastes storage and write overhead — check whether the prefix property already covers your query patterns with fewer indexes.
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.