MongoServerError: Executor error during find command :: caused by ::
Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting.
The query worked in development with 5,000 documents. In production, with 20 million, it fails, or on newer versions it quietly gets slow. The quick fix everyone reaches for is allowDiskUse. The real fix is usually an index.
Why it happens
When MongoDB can't return documents in the requested order straight from an index, it has to collect every matching document and sort them in memory. This is a blocking sort: nothing is returned until all matches are sorted. MongoDB caps that memory at 100 MB per sort stage. Above that, the query either fails or has to spill to temporary files on disk.
Since MongoDB 6.0, the allowDiskUseByDefault server parameter is true, so many deployments now spill to disk instead of failing. You'll still see the error when disk use is disabled (explicitly, by the driver, or on some hosted tiers that don't allow it), and even when it doesn't fail, a disk-spilling sort over millions of documents is slow.
Confirm it with explain
db.orders.find({ status: "shipped" })
.sort({ createdAt: -1 })
.limit(50)
.explain("executionStats")
Look for a SORT stage in winningPlan. If it's there, the index isn't providing the order. Compare totalDocsExamined with nReturned: examining 2,000,000 documents to return 50 is the smoking gun.
The fix: an index that matches filter and sort
Follow the ESR rule for compound index field order:
- Equality fields first (),
