What this thread does
Do first: run db.orders.explain("executionStats").aggregate(pipeline) with representative parameters and locate the first stage that greatly increases scan work, memory or row count.
Short answer
As of November 2026, target MongoDB 8.0 (release notes, major release); inspect db.version() before applying the version-specific references. Use an index for the initial equality/filter/sort pattern, then reduce semantically independent input before blocking or expanding stages. Permission to spill is not a latency optimization.
Choose / don't choose
- Compound index: choose when a frequent selective filter and required sort can share it; don't add indexes blindly to a rare query on a write-heavy collection. Equality fields first; then sort before range for ordered retrieval, or a highly selective range before sort when reducing scans wins (ESR).
- Disk-backed sort/group: choose for an intentionally large bounded report; don't use it to hide an API query exceeding its latency budget (limits).
- Pipeline redesign: choose when unwind/join expansion or grouping dominates; don't expect an index on the original collection to sort arbitrary derived group output.
Not for: choosing an index for a simple MongoDB find query; see mongodb-query-slow-with-many-documents-compound-index-equality-sort-range.
Settings that matter
| Setting or flag | Value / default | Applies to | Source |
|---|---|---|---|
allowDiskUse | Explicit false to surface unsupported memory growth in a latency-sensitive query; true for an accepted spill. Overrides server behavior. | MongoDB 8.0 | aggregate command |
allowDiskUseByDefault | Since 6.0, controls spill behavior for eligible stages beyond 100 MB; inspect deployment policy instead of assuming each query opts in | MongoDB 8.0 | limits |
maxTimeMS | Positive integer milliseconds from the query's share of the API budget; 0/omitted is unbounded in this command reference. Interrupt points can delay cancellation. | MongoDB 8.0 | aggregate command |
| Compound index keys | Ensure that equality fields always come first; adapt to the actual predicate | MongoDB 8.0 | ESR, createIndex |
collation | Operation and index must use the same collation for indexed string comparisons. Preserve existing locale/case/accent semantics. | MongoDB 8.0 | collation |
$limit | Place the required top-N limit adjacent to $sort only when no intervening cardinality-changing stage is required | MongoDB 8.0 | optimization |
Order of operations
1. Preserve the original output and executionStats explain. Compare nReturned, totalDocsExamined, totalKeysExamined, COLLSCAN/IXSCAN, and blocking SORT; inspect usedDisk, spill counts and per-stage row expansion. Treat an IXSCAN with huge examined counts as insufficient (explain fields). 2. Move $match before $sort if it uses available unchanged fields. A filter requiring a computed projection cannot move ahead of its computation. Move a parent-only match before $unwind when equivalent, but do not move an element filter and assume identical arrays/null behavior. Keep a required $group's inputs and accumulator semantics intact; do not move a limit before it (sequence optimization). 3. Build the candidate equality/sort/range index with the intended collation. Repeat the same query and output comparison. Index-supported sort generally needs the original indexed fields before stages such as $unwind and $group alter the document stream (optimization). 4. If $lookup dominates, inspect foreign indexesUsed, collectionScans and row counts. Put a selective independent outer filter first. Let the documented adjacent lookup/unwind/match optimization preserve semantics rather than manually discarding required children ($lookup). 5. Compare normal application latency and identical ordered IDs/totals after each single change. Explain ignores the plan cache and its timing need not match steady-state calls (caveats).
Known failures and fixes
| Error (short quote) | Cause | Fix | Source |
|---|---|---|---|
operation exceeded time limit | A query reached maxTimeMS; Chinmaya Das's report shows a COLLSCAN | Inspect examined/returned counts, add a suitable filter index or reduce equivalent input; retain the API limit instead of raising it reflexively | report |
Sort exceeded memory limit | A blocking stage exceeds its permitted memory without spill permission | Prefer index-supported sort or equivalent smaller input; allow disk only for the accepted report branch and inspect usedDisk | Prasad Saya, February 18, 2021, current limits |
Joby Joseph's January 9, 2024 aggregation report shows a foreign index, zero collection scans and row expansion to 80,368; the author identifies unwind as the expense. It is an older workload example, not a timing prediction for 8.0.
Missing
- No actual pipeline, selectivity distribution, collation or API latency budget is provided. The example index and positive maxTimeMS policy are candidates, not a justified production index or universal timeout.
Checked
2026-11-12; command, explain, ESR, collation, index, optimization, lookup and limit references, release notes and dated firsthand reports read. No database commands executed.
Additional sources read: reference.
Started from a post by @MongoDB, packaged by the editor. Original post