Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

explain('executionStats') shows a query with nReturned: 20, totalKeysExamined: 450000, totalDocsExamined: 450000 and a SORT stage that used disk. What is wrong and how do you fix it?

The query uses an index that matches its filter poorly, so MongoDB examines 450,000 index keys and 450,000 documents to return only 20, and the SORT stage shows the index does not provide the requested order, so all those candidates were sorted in memory until the sort exceeded its memory limit and spilled to disk. The fix is a compound index built for this query shape following equality, sort, range, then verifying that the winning plan uses it with no SORT stage and keys examined close to 20. We should also check the plan cache, which can keep a poor plan for the query shape, and reduce what we return with a projection, ideally making the query covered.

Why this question is asked

explain('executionStats') is the most useful debugging tool in MongoDB, and this output is a textbook example of a query that works on a test database and falls over in production. Interviewers give us numbers like these to see whether we can read them: which ratio matters, what a SORT stage means, and what 'used disk' tells us. In this answer, we will recap the fields of executionStats, read this output line by line, reproduce the problem with a concrete query, fix it with the right index, and then look at the plan cache and projections, which decide whether the fix actually sticks and how far it can go.

1A Quick Recap of executionStats

explain('executionStats') runs the query and reports what the winning plan did. nReturned is how many documents came out. totalKeysExamined is how many index entries were read. totalDocsExamined is how many documents were fetched from storage. The plan is a tree of stages: IXSCAN reads an index, FETCH loads documents, SORT sorts in memory, COLLSCAN reads the whole collection, and LIMIT stops early.

The key health signal is the ratio of examined to returned. Ideally totalKeysExamined and totalDocsExamined are close to nReturned, meaning every entry read was useful. Here the ratio is 450,000 to 20, so 99.99 percent of the work was thrown away.

2Reading This Output

Let us reproduce a query that produces exactly this shape. The collection has an index on status only, and the query filters on status and region and sorts by createdAt.

Java
db.orders.createIndex({ status: 1 }); // the only relevant index
db.orders.find({ status: "OPEN", region: "EU" })
.sort({ createdAt: -1 }).limit(20)
.explain("executionStats");
// stage: LIMIT -> SORT (usedDisk: true) -> FETCH (filter: region "EU") -> IXSCAN { status: 1 }
// nReturned: 20
// totalKeysExamined: 450000 every OPEN order
// totalDocsExamined: 450000 each one fetched to test region
// SORT: usedDisk: true, memLimit exceeded
Step throughWhat the slow plan does
  1. IXSCAN on {status: 1}450,000 OPEN entries
  2. FETCH every document450,000 reads to test region
  3. Keep EU ordersstill many thousands
  4. SORT by createdAtover 100 MB, spills to disk
  5. LIMIT 20only now can it stop

5 steps in order. Play them, or step through them one at a time.

Every stage before LIMIT does work proportional to all OPEN orders, not to 20.

Now each number explains itself. The IXSCAN on status reads every OPEN order, 450,000 entries, because the index knows nothing about region. FETCH loads all 450,000 documents to check region, which is why docs examined equals keys examined. The index has no createdAt, so the results are not in the requested order, and MongoDB must add a SORT stage that collects every surviving candidate before it can return the first 20. That sort is a blocking stage with a memory limit, 100 MB by default, and because the candidates exceeded it, the sort spilled to temporary files on disk, shown as usedDisk: true. Disk use for find sorts is allowed by default in MongoDB 6.0 and later; in older versions this query would have failed instead, so check your version.

3Fix: An Index Built for This Query Shape

A query shape is the combination of filter fields, sort and projection, ignoring the actual values. We design an index for this shape with the equality, sort, range guideline: equality fields first, then the sort field, then any range fields.

Java
db.orders.createIndex({ status: 1, region: 1, createdAt: -1 });
db.orders.find({ status: "OPEN", region: "EU" })
.sort({ createdAt: -1 }).limit(20)
.explain("executionStats");
// stage: LIMIT -> FETCH -> IXSCAN { status: 1, region: 1, createdAt: -1 }
// no SORT stage
// nReturned: 20, totalKeysExamined: 20, totalDocsExamined: 20

With status and region first, all matching entries sit in one contiguous stretch of the index, already ordered by createdAt, so MongoDB reads exactly 20 entries and fetches 20 documents. The SORT stage disappears because the index supplies the order, and with it the disk spill. We verify by looking at the winningPlan and the three numbers, not by assuming. Once confirmed, the old {status: 1} index may be redundant, since our new index starts with the same field, and can be considered for removal later.

4Check the Plan Cache

There is a catch that makes fixes appear not to work. When a query shape has several candidate indexes, MongoDB races them briefly, picks the winner, and caches that choice for the shape. Later queries with the same shape reuse the cached plan. If the cache was filled when the data looked different, or before our new index existed in some cases, a poor plan can stay in use until it is evicted or replanned, for example because its performance drops sharply, the index set changes, or the server restarts.

Java
db.orders.getPlanCache().list(); // cached plans for this collection
db.orders.getPlanCache().clear(); // drop them so the next query replans
// for a stubborn case, force the index while investigating
db.orders.find({ status: "OPEN", region: "EU" })
.sort({ createdAt: -1 }).hint({ status: 1, region: 1, createdAt: -1 });

Creating an index normally clears the cache for that collection, but checking costs nothing. hint() is useful for testing that the index really is better; in application code it is a last resort, because it stops MongoDB from adapting when data changes. The profiler or slow query log, which records planSummary for slow operations, tells us which plan production queries actually use.

5Return Less: Projections and Covered Queries

Finally, we reduce the work after the index. If the page only shows order id, total and date, a projection avoids sending whole documents over the network. If every field the query filters, sorts and returns is in the index, MongoDB can answer from the index alone, which is called a covered query, and totalDocsExamined drops to 0.

Java
db.orders.createIndex({ status: 1, region: 1, createdAt: -1, total: 1 });
db.orders.find({ status: "OPEN", region: "EU" },
{ _id: 0, createdAt: 1, total: 1 })
.sort({ createdAt: -1 }).limit(20)
.explain("executionStats");
// stage: LIMIT -> PROJECTION_COVERED -> IXSCAN
// totalKeysExamined: 20, totalDocsExamined: 0

Notice _id: 0: _id is returned by default, and since it is not in this index, including it would force a FETCH. A covered query is a nice extra for very hot read paths, but a wider index costs memory and write time, so we use it where the gain is measured.

6Follow-up questions

Why did the sort spill rather than fail?

Since MongoDB 4.4 find() accepts allowDiskUse, and since 6.0 the server parameter allowDiskUseByDefault is true, so blocking sorts that exceed the 100 MB limit write temporary files. Spilling avoids an error but is slow, so usedDisk: true should be treated as a warning, not a success.

What if the filter used a range, like createdAt in the last week?

Then ESR still applies: equality fields first, then the sort field, then the range field. If the sort and the range are on the same field, the field goes after the equality fields and serves both.

How do I find such queries before users complain?

Enable the profiler at a slowms threshold or read the slow query log, and look for a high ratio of docsExamined to nreturned, COLLSCAN, or a SORT stage with usedDisk. Managed services also offer index suggestions built from this data.

7Conclusion

In this answer, we read an explain output where 450,000 keys and documents were examined to return 20, which means the index matched the filter poorly, and a SORT stage that spilled to disk, which means the index did not provide the order and the sort exceeded its memory limit. We fixed it with a compound index following equality, sort, range and verified the winning plan, checked the plan cache so a stale plan does not hide the fix, and reduced the work further with a projection and, where worthwhile, a covered query.

What to say in the interviewAbout 90 seconds aloud

Open with

The ratio is the first thing I look at: 450,000 keys and 450,000 documents examined to return 20 means the index MongoDB used matches only part of the filter, so it reads a huge range of entries and fetches every document to test the remaining conditions.

Then, if they want more

The SORT stage tells me the index does not provide the requested order, so MongoDB had to collect all those candidates and sort them in memory, and because that exceeded the blocking sort limit, a hundred megabytes by default, it spilled to disk. On 6.0 and later disk use is allowed by default, so it ran slowly instead of failing.

The fix is an index built for this query shape using equality, sort, range: equality fields from the filter first, then the sort field, then any range fields. Then I run explain again and expect an IXSCAN on the new index, no SORT stage, and keys and docs examined close to twenty.

I would also check the plan cache, because MongoDB caches the winning plan per query shape and a poor plan can stick until it is replanned, so I list or clear it and check the slow query log for the plan production actually uses.

Finally, a projection of only the needed fields, and possibly a covered query, cuts the remaining work.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
MongoDB manual
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "explain('executionStats') shows a query with nReturned: 20, totalKeysExamined: 450000...": https://scrivio-interview-library.netlify.app/databases/mongodb/c20bce6c58/