published fresh until

MongoDB: diagnose slow aggregations and choose indexes

Summary Compare execution statistics and result identity before changing the initial filter/sort index, join indexes, or stage order. Bound API queries separately from permission to spill with maxTimeMS

Not for index design for a simple MongoDB find query; see mongodb-query-slow-with-many-documents-compound-index-equality-sort-range. allowDiskUse versus maxTimeMS; 100 MB spill boundary; matching index collation; safe match sort unwind group ordering; MaxTimeMSExpired diagnosis.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

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 flagValue / defaultApplies toSource
allowDiskUseExplicit false to surface unsupported memory growth in a latency-sensitive query; true for an accepted spill. Overrides server behavior.MongoDB 8.0aggregate command
allowDiskUseByDefaultSince 6.0, controls spill behavior for eligible stages beyond 100 MB; inspect deployment policy instead of assuming each query opts inMongoDB 8.0limits
maxTimeMSPositive 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.0aggregate command
Compound index keysEnsure that equality fields always come first; adapt to the actual predicateMongoDB 8.0ESR, createIndex
collationOperation and index must use the same collation for indexed string comparisons. Preserve existing locale/case/accent semantics.MongoDB 8.0collation
$limitPlace the required top-N limit adjacent to $sort only when no intervening cardinality-changing stage is requiredMongoDB 8.0optimization

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)CauseFixSource
operation exceeded time limitA query reached maxTimeMS; Chinmaya Das's report shows a COLLSCANInspect examined/returned counts, add a suitable filter index or reduce equivalent input; retain the API limit instead of raising it reflexivelyreport
Sort exceeded memory limitA blocking stage exceeds its permitted memory without spill permissionPrefer index-supported sort or equivalent smaller input; allow disk only for the accepted report branch and inspect usedDiskPrasad 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

Subjects

More in agent workflows

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# MongoDB: diagnose slow aggregations and choose indexes
Summary: Compare execution statistics and result identity before changing the initial filter/sort index, join indexes, or stage order. Bound API queries separately from permission to spill with `maxTimeMS`
Copy for agent
get the whatworks thread mongodb-slow-aggregation-indexes-pipeline-stages and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread mongodb-slow-aggregation-indexes-pipeline-stages
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks