Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

A query is db.orders.find({status: 'OPEN', customerId: 42}).sort({createdAt: -1}). Which compound index would you create, and what is the equality, sort, range guideline?

Create the compound index {customerId: 1, status: 1, createdAt: -1}: the two equality fields first, then the sort field. This follows the ESR guideline, which orders compound index keys as Equality fields, then Sort fields, then Range fields. With that index MongoDB jumps to the entries for customer 42 with status OPEN, which are already stored in createdAt order, so it returns results without an in-memory SORT stage, and explain('executionStats') should show an IXSCAN, no SORT, and totalKeysExamined close to nReturned.

Why this question is asked

Index design is where most MongoDB performance is won or lost, and compound indexes are where most mistakes happen. The order of fields in a compound index is not cosmetic: the same three fields in a different order can make a query use a fast, ordered scan or force it to read thousands of entries and sort them in memory. Interviewers ask this simple-looking query to see whether we can reason about that order. In this answer, we will recap how a compound index is laid out, build the right index for this query and see why it works, compare it with wrong orders, introduce the ESR guideline, and finish by proving the result with explain.

1A Quick Recap of Compound Indexes

A MongoDB index is a B-tree of keys, each pointing to a document. A compound index has keys made of several fields, sorted first by the first field, then by the second within equal first values, and so on, like a phone book sorted by last name and then first name. Each field also has a direction, 1 for ascending and -1 for descending.

Because of that layout, an index is useful for a query when the query can jump to one contiguous stretch of the tree and read it in order. Equality conditions on the leading fields narrow the tree to one stretch. Within that stretch, the next field's order is the order the entries are already in, which is what lets the index provide a sort for free.

2Building the Index for This Query

The query filters on two exact values and sorts by a third field.

Java
db.orders.createIndex({ customerId: 1, status: 1, createdAt: -1 });
db.orders.find({ status: "OPEN", customerId: 42 })
.sort({ createdAt: -1 })
.limit(20);
// IXSCAN { customerId: 1, status: 1, createdAt: -1 }
// no SORT stage: entries are read newest first
Index entries for customer 42, in B-tree order
customerIdstatuscreatedAtRead by the query?
42CLOSED2026-10-30no, skipped by the seek
42CLOSED2026-09-12no
42OPEN2026-11-05yes, first result
42OPEN2026-11-02yes, second result
42OPEN2026-10-28yes, third result
43OPEN2026-11-06no, other customer
Equality fields narrow the scan to one contiguous stretch, already sorted by createdAt.

Notice that the order of fields in the filter document does not matter; MongoDB matches conditions to index fields by name. What matters is the order in the index. With customerId and status first, all entries for customer 42 and status OPEN sit next to each other in the B-tree, and within that stretch they are ordered by createdAt descending. So MongoDB seeks to the start of the stretch, reads the first 20 entries, fetches those 20 documents, and stops. The cost is proportional to what we return, not to how many orders the customer has.

3What Goes Wrong With Other Orders

Compare two plausible alternatives.

Java
// Sort field first
db.orders.createIndex({ createdAt: -1, customerId: 1, status: 1 });
// scans entries newest first for ALL customers, filtering as it goes
// fine if customer 42 ordered recently, terrible if not
// Equality fields only
db.orders.createIndex({ customerId: 1, status: 1 });
// finds the matching entries, but they are not in createdAt order
// FETCH -> SORT in memory over every open order of customer 42

With the sort field first, the index gives the right order, but the matching entries are scattered across the whole tree, so MongoDB may read a huge number of entries to find 20 for this customer. With only the equality fields, MongoDB finds the right stretch but must fetch all matching documents and sort them in memory, which is a blocking SORT stage that grows with the customer's order count and is limited in memory. Our index avoids both problems.

4The Equality, Sort, Range Guideline

The rule behind our choice is called ESR: put fields tested with Equality first, then fields used for Sort, then fields tested with a Range, such as $gt, $lt or $in with many values in some cases. The reason is the layout we saw. Equality fields narrow to one stretch whose next field is sorted. A sort field placed next gives the order for free. A range field placed before the sort field would break the stretch into many smaller stretches, each sorted separately, so MongoDB would have to merge or sort them.

Suppose the query also asked for orders with total greater than 100. The ESR index would be {customerId: 1, status: 1, createdAt: -1, total: 1}. MongoDB can then check the range on total from the index entries while reading in createdAt order, without a sort. If total came before createdAt, the order would be lost.

5Proving It With explain

We never trust an index design until explain confirms it.

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

The signals are: the winning plan has an IXSCAN on our index and no SORT stage, and totalKeysExamined and totalDocsExamined are close to nReturned. A ratio of 20 examined to 20 returned is ideal. If we saw 20 returned but 20,000 keys examined, or a SORT stage, the index would not be serving the query the way we intended.

6Ordering the Equality Fields

Between customerId and status, which comes first? For this query it does not matter for correctness or speed, because both are equality conditions, and either order gives one contiguous stretch. The choice matters for reuse. An index can serve any query on a prefix of its fields, so {customerId: 1, status: 1, createdAt: -1} also serves 'all orders of customer 42', while {status: 1, customerId: 1, ...} serves 'all OPEN orders'. We pick the order whose prefixes other frequent queries need, which often lets one index replace two.

7Follow-up questions

Does the direction of createdAt matter?

For a single sort field, not much: MongoDB can scan an index backwards, so {createdAt: 1} also serves sort({createdAt: -1}). Direction matters when sorting on several fields in mixed directions, such as sort({a: 1, b: -1}), where the index must match that pattern or its exact reverse.

Where does $in fit in ESR?

$in on a few values behaves partly like equality, but sorting across several $in values requires a merge of several sorted stretches, and with many values it acts like a range. Check explain for a SORT_MERGE or SORT stage and treat large $in lists as range fields.

Is the index still useful without the sort?

Yes. A query with just the two equality conditions uses the same index, and a query on customerId alone uses its prefix. That reuse is part of why we order fields carefully.

8Conclusion

In this answer, we saw that a compound index is sorted field by field, so equality fields first narrow the scan to one contiguous stretch whose next field is already in order. For this query the index {customerId: 1, status: 1, createdAt: -1} returns the first 20 results without an in-memory sort, while other orders either scan too much or sort in memory. The ESR guideline, equality then sort then range, generalises this, and explain('executionStats') proves it with an IXSCAN, no SORT stage and keys examined close to documents returned.

What to say in the interviewAbout 80 seconds aloud

Open with

I would create a compound index on customerId ascending, status ascending, then createdAt descending. The reasoning is the equality, sort, range guideline. A compound index is a B-tree sorted by the first field, then the second, and so on.

Then, if they want more

If the equality fields come first, all entries for customer 42 with status OPEN sit in one contiguous stretch, and within that stretch the next field, createdAt, is already in order. So MongoDB seeks to the stretch, reads the first twenty entries newest first, fetches twenty documents, and stops, with no in-memory SORT stage.

If I put createdAt first, the order is right but matching entries are scattered across all customers. If I index only the equality fields, MongoDB has to sort all of the customer's open orders in memory. Range conditions go last because they would break the sorted stretch.

I would confirm it with explain executionStats: an IXSCAN with no SORT stage, and totalKeysExamined and totalDocsExamined close to nReturned. The order between customerId and status does not change correctness for this query, so I choose the one whose prefix other queries can reuse, for example customerId first so the same index serves all orders of a customer.

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 "A query is db.orders.find({status: 'OPEN', customerId: 42}).sort({createdAt: -1}). Which...": https://scrivio-interview-library.netlify.app/databases/mongodb/6ed6bc0f78/