MongoDB throws QueryExceededMemoryLimitNoDiskUseAllowed when a blocking aggregation stage needs more RAM than the default limit but the query did not ask to spill to disk, so the plan executor aborts with a sort memory error.
The QueryExceededMemoryLimitNoDiskUseAllowed error is raised by MongoDB's plan executor when a blocking stage such as `$sort`, `$group`, `$lookup`, or Atlas Search has to buffer more documents than the configured in-memory limit but the operation is not allowed to use temporary disk files. MongoDB keeps the intermediate results in RAM—100 MB by default in most builds (and 32 MB on shared Atlas tiers)—and rejects the request as soon as the working set exceeds that threshold. The driver surfaces this as a MongoServerError or OperationFailure with the PlanExecutor message "Sort exceeded memory limit ... but did not opt in to external sorting" and the code name `QueryExceededMemoryLimitNoDiskUseAllowed` (code 292).
Pass { allowDiskUse: true } when calling aggregate so MongoDB can spill to disk instead of keeping everything in RAM.
// mongosh or mongo shell
const pipeline = [...];
printjson(db.collection.aggregate(pipeline, { allowDiskUse: true }).toArray());
// Node.js driver
const cursor = collection.aggregate(pipeline, { allowDiskUse: true });
await cursor.toArray();
// PyMongo
result = list(collection.aggregate(pipeline, allowDiskUse=True))
If you rely on find().sort(), convert to an aggregation with a final $sort and the same flag (modern drivers also expose .allowDiskUse(true) on cursors). Enabling disk use is the quickest fix, but monitor I/O as spilling can slow other queries.
Trim the data before MongoDB has to sort it. Push $match, $project, and $limit ahead of $sort or $group, and only carry the fields you actually need.
const pipeline = [
{ $match: { status: 'active' } },
{ $project: { _id: 0, batteryId: 1, time: 1 } },
{ $sort: { time: -1 } },
{ $limit: 1000 },
// rest of the stages
];
Also make sure indexes support the sort/group keys so MongoDB can stream results instead of buffering huge sets. If arrays or lookups inflate each document, consider splitting the pipeline or using $setWindowFields to operate in chunks.
Run .explain('executionStats') on the pipeline to see which stage is using the most RAM and how far over the limit it went.
const plan = await collection.aggregate(pipeline, { allowDiskUse: false }).explain('executionStats');
console.log('Max blocking sort bytes:', plan.maxBlockingSortBytes);
console.log(plan.stages);
The output shows whether SORT or GROUP is buffering documents, how many docs it processed, and whether allowDiskUse was false. Use this information to rearrange stages, narrow the input, or confirm that you need to raise the limit before rerunning with allowDiskUse enabled.
Self-managed mongod instances let you increase the default 100 MB buffer via the internalQueryExecMaxBlockingSortBytes parameter.
// mongosh
db.adminCommand({
setParameter: 1,
internalQueryExecMaxBlockingSortBytes: 335544320,
});
Or put this in mongod.conf and restart:
setParameter:
internalQueryExecMaxBlockingSortBytes: 335544320
Atlas free/shared tiers and serverless clusters stay limited to 32 MB, so in those environments you must optimize the query or upgrade to a dedicated tier. After raising the limit, watch for memory pressure because very large buffers can hurt concurrency.
QueryExceededMemoryLimitNoDiskUseAllowed maps to code 292 and is part of SERVER-42659, which introduced a dedicated error name for sorts that exceed their memory budget. The default cap is 100 MB and applies to blocking sorts, groups, and facets; Atlas M0/M2/M5 clusters and serverless deployments are stuck at 32 MB with no server-side knob. Enabling allowDiskUse trades memory pressure for disk I/O, so use indexes + filtering to keep the working set small before letting MongoDB spill. The internalQueryExecMaxBlockingSortBytes parameter (or the mongod.conf setParameter entry above) lets you increase the limit on self-hosted servers, but raising it too far increases RAM usage and can degrade other operations. Always re-run explain and monitor metrics after making the change.
StaleShardVersion: shard version mismatch
How to fix "StaleShardVersion: shard version mismatch" in MongoDB
MongoOperationTimeoutError: Operation timed out
How to fix "MongoOperationTimeoutError: Operation timed out" in MongoDB
MissingSchemaError: Schema hasn't been registered for model
How to fix "MissingSchemaError: Schema hasn't been registered for model" in MongoDB/Mongoose
CastError: Cast to ObjectId failed for value "abc123" at path "_id"
How to fix "CastError: Cast to ObjectId failed" in MongoDB
OverwriteModelError: Cannot overwrite model once compiled
How to fix "OverwriteModelError: Cannot overwrite model once compiled" in MongoDB