Compound index order follows the ESR rule: Equality fields first, then Sort fields, then Range fields. An index on {status: 1, createdAt: -1, price: 1} serves status = "paid" ORDER BY createdAt DESC perfectly, and the same fields in a different order do not. Getting ESR right is most of index design in MongoDB, and it is the thing most often got wrong.
A compound index serves prefixes. {a: 1, b: 1, c: 1} also serves queries on {a} and {a, b}, so three separate single-field indexes are usually waste. Index count matters: every index is maintained on every write.
Index types to know. Multikey indexes are created automatically on array fields and index each element - note that a compound index may contain at most one array field. TTL indexes delete documents after a set age, which is the right way to expire sessions and logs; the background task runs roughly every 60 seconds, so expiry is not instant. Partial indexes cover only documents matching a filter and are often dramatically smaller - an index on {status: 1} partialFilterExpression: {status: "pending"} indexes the 200 pending orders rather than the 10 million historic ones. Sparse is the older, weaker form. Text indexes do language-aware search with stemming and stop words; Atlas Search is the much more capable option if you are on Atlas.
Reading explain. Use explain("executionStats"). The numbers that matter: totalDocsExamined against nReturned - these should be close; a ratio of thousands means the index is not doing its job. COLLSCAN in the winning plan means no index was used at all. totalKeysExamined much larger than nReturned means the index is being scanned rather than seeked. And SORT as a stage means an in-memory sort, which fails outright above 100 MB unless you allow disk use - the index should have provided the order.
Aggregation optimisation. $match and $sort before $group and $lookup, always. $project early to reduce document size through the pipeline. Watch for $lookup on the hot path - it is a join and it runs per document. allowDiskUse: true lets stages spill, which prevents the 100 MB failure and is slower than fixing the pipeline.
The working set, not the data size, drives memory. MongoDB with WiredTiger keeps frequently accessed documents and index pages in cache (by default half of RAM minus a gigabyte). What must fit is the working set: the indexes plus the documents you actually touch. A 2 TB collection where queries only ever read last week's data has a small working set and performs well on modest hardware; a 50 GB collection with random access across all of it does not. The single most useful memory metric is the WiredTiger cache eviction rate - rising evictions mean the working set no longer fits, and that is the moment performance falls off a cliff rather than degrading gently.
Laboratory exercise 4 - a measured improvement.
Load at least five million documents with realistic skew. Declare a baseline: five queries with p50, p95 and p99, plus totalDocsExamined, nReturned and the winning plan stage for each.
Apply techniques one at a time and re-measure: a compound index built using ESR, a partial index on a selective status, a multikey index on an array field, a TTL index on a log collection, and a text index for catalogue search.
Demonstrate the in-memory sort failure: write a sort over more than 100 MB without a supporting index, capture the error, then add the index and show it succeed.
Then demonstrate the working set: shrink the WiredTiger cache, run a query touching more data than fits, and record the eviction rate and the latency change. Restore it and re-measure.
Include one index that made things worse.
Deliverable: the benchmark report with all percentiles at each step, explain output before and after, the sort failure and its fix, the working set experiment with eviction metrics, and the index that did not help with an explanation of why.
// ------------------------------------------------------------------
// THE ESR RULE: Equality, Sort, Range. In that order.
// ------------------------------------------------------------------
// The query:
// find({status: "paid", price: {$lt: 100}}).sort({placedAt: -1})
// ^^ equality ^^ range ^^ sort
db.orders.createIndex(
{ status: 1, // E - equality first
placedAt: -1, // S - then the sort field
price: 1 } // R - range last
);
// The same three fields in a different order do NOT serve this query
// as well, and getting ESR right is most of index design in MongoDB.
// A compound index serves its PREFIXES, so this one also covers
// {status} and {status, placedAt}. Three separate single-field
// indexes would be waste - and every index is maintained on every
// write.
db.orders.getIndexes();
// ------------------------------------------------------------------
// PARTIAL: often dramatically smaller.
// ------------------------------------------------------------------
db.orders.createIndex(
{ status: 1, placedAt: -1 },
{ partialFilterExpression: { status: {$in: ["pending", "processing"]} } }
);
// Indexes the 200 open orders, not the 10,000,000 historic ones.
// Caveat: the query must be provably within the filter for the
// optimiser to use it - `find({status: "pending"})` yes,
// `find({status: {$ne: "paid"}})` no.
// MULTIKEY: automatic on arrays, one element per key.
db.product.createIndex({ tags: 1 });
db.product.createIndex({ "variants.sku": 1 });
// At most ONE array field per compound index. {tags:1, variants:1}
// is rejected if both are arrays.
// TTL: the right way to expire sessions and logs.
db.session.createIndex({ lastSeen: 1 }, { expireAfterSeconds: 3600 });
// The background task runs about every 60 s, so expiry is NOT
// instant. Do not build a business rule on exact timing.
// TEXT: language-aware, with stemming and stop words.
db.product.createIndex(
{ name: "text", description: "text" },
{ weights: { name: 10, description: 1 }, default_language: "english" }
);
db.product.find({$text: {$search: "mechanical keyboard"}},
{score: {$meta: "textScore"}}).sort({score: {$meta: "textScore"}});
// One text index per collection, maximum. On Atlas, Atlas Search is
// far more capable and is a different mechanism.
// ------------------------------------------------------------------
// EXPLAIN: the four numbers that matter.
// ------------------------------------------------------------------
const e = db.orders.find({status: "paid", price: {$lt: NumberDecimal("100")}})
.sort({placedAt: -1}).explain("executionStats");
e.executionStats;
// nReturned : 1,204
// totalKeysExamined : 1,204 <- seeking, not scanning: good
// totalDocsExamined : 1,204 <- close to nReturned: good
// executionTimeMillis : 8
//
// BAD looks like this:
// nReturned : 1,204
// totalDocsExamined : 4,012,338 <- ratio in the thousands
// winningPlan.stage : "COLLSCAN" <- no index used AT ALL
// winningPlan has : "SORT" <- in-memory sort; the index
// should have given the order
e.queryPlanner.winningPlan;
e.queryPlanner.rejectedPlans.length;
// THE SORT FAILURE. Demonstrate it, then fix it:
db.orders.find({}).sort({unindexedField: 1}).toArray();
// -> MongoServerError: Sort exceeded memory limit of 104857600 bytes
// and did not opt in to external sorting
// An in-memory sort FAILS OUTRIGHT above 100 MB. allowDiskUse works
// and is slower; the index is the fix.
// ------------------------------------------------------------------
// Aggregation optimisation.
// ------------------------------------------------------------------
db.orders.aggregate([
{ $match: { status: "paid", placedAt: {$gte: ISODate("2026-01-01")} } },
{ $sort: { placedAt: -1 } }, // before $group, so the index serves it
{ $project: { lines: 1, placedAt: 1, total: 1 } }, // shrink early
{ $unwind: "$lines" },
{ $group: { _id: "$lines.productId", revenue: {$sum: "$lines.unitPrice"} } }
], { allowDiskUse: true }).explain("executionStats");
// Read the explain: did $match use an index? Did $sort become a
// SORT stage or did the index supply the order?
// ------------------------------------------------------------------
// THE WORKING SET drives memory, not the data size.
// ------------------------------------------------------------------
const s = db.serverStatus().wiredTiger.cache;
({
bytesInCache: s["bytes currently in the cache"],
maxBytes: s["maximum bytes configured"],
pctUsed: (100 * s["bytes currently in the cache"] /
s["maximum bytes configured"]).toFixed(1),
// THE metric. Rising evictions mean the working set no longer fits,
// and performance falls off a cliff rather than degrading gently.
evictedPages: s["unmodified pages evicted"],
readIntoCache: s["pages read into cache"],
appThreadsEvicting: s["pages evicted by application threads"]
});
// appThreadsEvicting > 0 is the alarm: your QUERY threads are now
// doing eviction work instead of answering queries.
db.customer.stats().indexSizes;
db.customer.totalIndexSize();
// What must fit in cache is: all the indexes you use, plus the
// documents you actually touch. A 2 TB collection queried only over
// last week has a small working set. A 50 GB collection with random
// access across all of it does not.
Open this example in the editor and change it. Nothing you type is saved.
Discussion
No questions on this topic yet. Sign in to ask the first one.