MongoDB · Opend practice case · Updated
Which index gets the newest 20 orders onto the screen?
A merchant dashboard reads one tenant’s open orders, sorted by creation time descending, with a page size of 20. The collection has millions of documents. A second dashboard adds a minimum order total. Do these screens need the same index?
Short answerUse the exact query shape to propose a compound index. Compare keys and documents examined, sort work and write cost on production-shaped data before deciding.
- Seek the prefix
tenantId = T9, status = open. These equality fields identify one contiguous index interval.
- Read in order
createdAt descending gives the requested order within that interval.
- Stop after 20
Fetch the matching documents for display. Add a stable tie-breaker if the result is paginated.
Translate the query into an access path
For the first screen, try { tenantId: 1, status: 1, createdAt: -1 }. A single-field time index could also return recent orders in order, but it may walk past many other merchants’ records. With a tenant-and-status prefix, the scan starts inside the relevant interval. If two orders can share a timestamp, include a unique tie-breaker in both the sort and the index when implementing a cursor.
Use a second workload to challenge the first design
Now require total above a high threshold. Putting the range field after the time field retains the requested order, but the engine might scan many entries to find 20 large orders. Putting a highly selective range before the sort can reduce the candidate set enough to make a small in-memory sort worthwhile. MongoDB’s equality, sort and range guidance describes both choices.
MongoDB compound index ordering ↗Explain what the measurements can prove
The sample runs below return the same 20 full documents. The compound index examines one key per result in this simplified case. That ratio says more about avoidable work than a single warm-cache timing. Inspect the winning plan for a blocking sort, then repeat with a large tenant and a sparse tenant. Finally measure representative writes and index size. Keeping a second index is a workload decision with an ongoing write cost.
MongoDB execution statistics ↗| Plan | Keys / docs examined | Returned |
|---|---|---|
| Time index only | 820 / 820 | 20 |
| Tenant, status, time | 20 / 20 | 20 |
| Collection scan and sort | 0 / 40,000 | 20 |
Try the follow-upA colleague sees zero keys examined and declares the collection scan fastest. How do you respond?
Read totalDocsExamined and the plan stages with the key count. The collection scan visited 40,000 documents. Zero index keys simply identifies the access path. To choose a plan, compare result correctness, resource use and repeated timings under representative traffic.