This error occurs when MongoDB attempts to sort documents without an index and the in-memory sort operation exceeds the configured memory limit (typically 32 MB by default). Solve it by creating indexes, enabling allowDiskUse, or optimizing your queries.
MongoDB has a memory limit for in-memory sorting operations. When you perform a sort without a supporting index, MongoDB tries to load all matching documents into memory and sort them. If this operation exceeds the default limit of 32 MB, MongoDB aborts the query to prevent server instability. This is a safety mechanism to prevent one query from consuming excessive server resources and impacting other database operations.
The most effective solution is to create an index on the field you are sorting by. This allows MongoDB to use the index for ordering, avoiding in-memory sorting entirely.
// For a single field sort
db.collection.createIndex({ fieldName: 1 });
// For a compound sort
db.collection.createIndex({ fieldName: 1, otherField: -1 });Verify the index is being used by examining the query execution plan:
db.collection.find({ /* query */ }).sort({ fieldName: 1 }).explain("executionStats");Look for COLLSCAN (collection scan) in the execution stats—if present, your index isn't being used.
If you're using aggregation and cannot create an index, enable external sorting by passing allowDiskUse: true. This allows MongoDB to write temporary data to disk when memory is exceeded.
db.collection.aggregate(
[ { $match: { /* filter */ } }, { $sort: { fieldName: 1 } } ],
{ allowDiskUse: true }
);Note: This is not available on MongoDB Atlas M0 (free tier) or M2/M5 shared clusters.
Move the $project stage before $sort to reduce document size in memory. Smaller documents consume less memory during sorting.
db.collection.aggregate([
{ $match: { /* your filter */ } },
{ $project: { fieldToSort: 1, otherNeeded: 1 } }, // Project first
{ $sort: { fieldToSort: 1 } } // Then sort
]);This is more efficient than sorting first and projecting after.
If indexing and disk use aren't options, temporarily increase the memory limit using setParameter. This requires admin privileges.
db.adminCommand({
setParameter: 1,
internalQueryExecMaxBlockingSortBytes: 335544320 // 320 MB
});Note: Setting this too high can cause server instability. Use only as a temporary measure while addressing the root cause.
MongoDB 6.0+ changed the default behavior: allowDiskUse is true by default, and pipeline stages requiring more than 100 MB of memory automatically spill to disk. If upgrading is possible, this eliminates the issue for many queries. For cursor-based sorts (not aggregation), you cannot use allowDiskUse—you must create an index. Always prefer indexing over allowDiskUse, as it provides better performance and avoids disk I/O overhead. When debugging, use explain("executionStats") to identify missing indexes and understand query performance.
DivergentArrayError: For your own good, using document.save() to update an array which was selected using an $elemMatch projection will not work
How to fix "DivergentArrayError: For your own good, using document.save() to update an array which was selected using an $elemMatch projection will not work" in MongoDB
MongoServerError: bad auth : authentication failed
How to fix "MongoServerError: bad auth : authentication failed" in MongoDB
CannotCreateIndex: Cannot create index
CannotCreateIndex: Cannot create index
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