How to fix ExceededMemoryLimit: Sort exceeded memory limit in MongoDB

MongoDBINTERMEDIATEHIGHUpdated Dec 29, 2025· 148 views

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.

Quick fix

Fixes ExceededMemoryLimit: Sort exceeded memory limit

// For a single field sort
db.collection.createIndex({ fieldName: 1 });

// For a compound sort
db.collection.createIndex({ fieldName: 1, otherField: -1 });
  1. Create an index on your sort field
  2. Enable allowDiskUse for aggregation pipelines
  3. Add projection before sorting in aggregation
  4. Increase memory limit for single-threaded queries (advanced)
mongodb — error
// For a single field sort
db.collection.createIndex({ fieldName: 1 });
// For a compound sort
db.collection.createIndex({ fieldName: 1, otherField: -1 });
ExceededMemoryLimit: Sort exceeded memory limit

What this error means

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.

Typical symptoms

  • Queries with sort clauses fail with "Sort exceeded memory limit" error
  • Error message includes byte count: "Sort exceeded memory limit of 104857600 bytes"
  • Error suggests passing allowDiskUse:true to opt in to external sorting
  • Sorting works on smaller datasets but fails when data grows
  • Aggregation pipeline with $sort stage fails without allowDiskUse option

Common causes

  1. No index exists on the sort field, forcing MongoDB to perform an in-memory sort on all matching documents
  2. Dataset size exceeds MongoDB memory allocation threshold for sorting (default 32-100 MB depending on version)
  3. Aggregation pipeline returns large intermediate result sets before sorting
  4. Using sort with inequality filters that exclude many indexed documents
  5. MongoDB version pre-6.0 where allowDiskUse defaults to false

How to fix "ExceededMemoryLimit: Sort exceeded memory limit"

1Create an index on your sort field

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.

javascript
// 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:

javascript
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.

2Enable allowDiskUse for aggregation pipelines

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.

javascript
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.

3Add projection before sorting in aggregation

Move the $project stage before $sort to reduce document size in memory. Smaller documents consume less memory during sorting.

javascript
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.

4Increase memory limit for single-threaded queries (advanced)

If indexing and disk use aren't options, temporarily increase the memory limit using setParameter. This requires admin privileges.

javascript
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.

Advanced notes

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.

Frequently asked questions

What does "ExceededMemoryLimit: Sort exceeded memory limit" mean?
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.
How do I fix "ExceededMemoryLimit: Sort exceeded memory limit"?
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.
What causes "ExceededMemoryLimit: Sort exceeded memory limit"?
No index exists on the sort field, forcing MongoDB to perform an in-memory sort on all matching documents Dataset size exceeds MongoDB memory allocation threshold for sorting (default 32-100 MB depending on version) Aggregation pipeline returns large intermediate result sets before sorting
Is the "ExceededMemoryLimit: Sort exceeded memory limit" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading