This article shows you how to build compound indexes in MongoDB, which are indexes that cover several fields at once, for the query shapes your application actually runs. If a page that filters by tenant and sorts by date takes seconds instead of milliseconds, the cause is usually field order. MongoDB can only use an index when your query matches its leading fields, so a badly ordered index sits idle while the database scans the whole collection. The short answer is the ESR rule, which puts equality filters first, then the field you sort on, then any range filters. By the end you will have a recipe for each common query shape, a way to see which indexes get used, and a safe way to drop the ones nobody uses.
How to verify
List the indexes and look at what queries actually use them via the $indexStats aggregation:
mongosh --host primary.example.internal:27017
use shop
db.orders.getIndexes()
db.orders.aggregate([{ $indexStats: {} }, { $project: { name: 1, accesses: 1 } }])
db.orders.find({ tenantId: 42, status: "paid" }).sort({ placedAt: -1 }).limit(20).explain("executionStats")
$indexStats.accesses.ops shows how many times each index was used since the last restart — an index with zero ops is dead weight. The explain output’s winningPlan.inputStage.stage should be IXSCAN with the right index name.
What’s happening
A compound index { a: 1, b: -1, c: 1 } sorts entries by a ascending, then by b descending, then by c ascending. The planner can use the index for any query that uses a, or a and b, or a, b, c — but not for a query that uses only b or only c. This is the prefix property. The “ESR rule” (Equality, Sort, Range) tells you the optimal field order: put equality predicates first, then the field you sort on, then range predicates. Get it backwards and the index works but the planner has to do a final sort in memory.
A covered query is one where every field the query needs is in the index — no document fetch required. That happens when the projection asks only for fields in the index (plus _id if you exclude it). Covered queries are an order of magnitude faster than uncovered ones for the same plan because there is no random IO to the underlying collection.
Multikey indexes are compound indexes where one or more fields is an array. MongoDB indexes every element of the array, which means index size and write cost grow with array length. You cannot have two array fields in the same compound index (because that would require indexing the cartesian product of both arrays — a combinatorial explosion).
The recipes
-
Equality + sort + range. Filter by tenant, sort by date, range on amount.
db.orders.createIndex({ tenantId: 1, placedAt: -1, amount: 1 }) db.orders.find({ tenantId: 42, amount: { $gte: 100 } }).sort({ placedAt: -1 }) -
Covered query. Index everything the query needs and exclude
_idfrom the projection.db.users.createIndex({ email: 1, name: 1, createdAt: 1 }) db.users.find({ email: "x@example.com" }, { _id: 0, name: 1, createdAt: 1 }) -
Multi-direction sort. Index direction matters when sorting on multiple fields with mixed directions.
db.feed.createIndex({ tenantId: 1, score: -1, createdAt: -1 }) db.feed.find({ tenantId: 42 }).sort({ score: -1, createdAt: -1 }) -
Unique constraint that doubles as a lookup. Don’t add a second index for the same prefix.
db.users.createIndex({ tenantId: 1, email: 1 }, { unique: true }) -
TTL on a date field. Auto-deletes documents N seconds after the indexed timestamp.
db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 }) -
Build in the background on a live system. Index builds in 4.2+ are non-blocking by default but still consume IO. Schedule for off-peak when possible.
db.adminCommand({ currentOp: true, $or: [{ op: "command", "command.createIndexes": { $exists: true } }] }) -
Retire unused indexes. An index that has zero
accesses.opsafter a full business cycle is dead weight — drop it.db.orders.aggregate([ { $indexStats: {} }, { $match: { "accesses.ops": 0 } }, { $project: { name: 1, since: "$accesses.since" } } ])
Operational notes
- Index intersection is real but rarely optimal. The planner can combine two single-field indexes —
{a: 1}and{b: 1}— but the combined cost almost always exceeds a purpose-built compound{a: 1, b: 1}. Prefer compound indexes for known query shapes. - Hashed indexes are not compoundable in interesting ways. A hashed field can only be hashed; range queries against it are not served. Use a hashed shard key for distribution, not for general querying.
- Wildcard indexes are a tax on writes.
{ "$**": 1 }indexes every field of every document. Useful for schemaless audit collections, expensive for hot write paths. - Index hints are sticky.
db.coll.find().hint("ix_name")forces a plan and bypasses planner statistics — useful as a workaround, dangerous as a long-term solution. Document every hint with a comment explaining why. db.coll.totalIndexSize()matters for memory. Indexes ideally live in RAM. Track index size againstmem.residentand replan when indexes start spilling to disk on every query.
Stack Harbor reviews MongoDB index sets as part of the operating model — usually finding two or three indexes covering the same access path and one critical query that is doing a COLLSCAN. We track $indexStats over the business cycle, retire dead indexes, and propose schema-aware indexes for the queries that drive cost. See /en/services/managed-operations/ for the engagement model.