Quick revision
The short answer
Blocking stages such as $group and $sort must hold their working data in memory and have a per-stage limit, traditionally 100 MB; when a stage exceeds it, the pipeline fails unless it is allowed to spill to temporary files on disk with allowDiskUse, which recent versions enable by default, so check your version. The better options are to reduce data early with $match and $project at the start, using indexes for the first $match and $sort, to pre-aggregate on a schedule with $merge into a summary collection, and to avoid $unwind followed by $group when an array operator such as $size or $reduce can do the work inside each document.
What to remember
In this answer, we saw that streaming stages need almost no memory while blocking stages such as $group and $sort hold their working data and are limited per stage, traditionally to 100 MB. allowDiskUse, on by default in recent versions, lets them spill to disk, but it is a slow safety valve and cannot lift the 16 MB document limit. The real fixes are to filter and project early with indexes on the first stages, to pre-aggregate incrementally with $merge into a summary collection, and to replace $unwind followed by $group with array operators such as $size and $reduce.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Blocking stages such as $group and $sort must hold their working data in memory and have a per-stage limit, traditionally 100 MB; when a stage exceeds it, the pipeline fails unless it is allowed to spill to temporary files on disk with allowDiskUse, which recent versions enable by default, so check your version. The better options are to reduce data early with $match and $project at the start, using indexes for the first $match and $sort, to pre-aggregate on a schedule with $merge into a summary collection, and to avoid $unwind followed by $group when an array operator such as $size or $reduce can do the work inside each document.
Why this question is asked
Aggregation pipelines often start small and grow with the data: a pipeline that ran in two seconds on a year of data fails three years later with a memory error. Simply turning on disk use makes the error go away, but the pipeline may now run for minutes and hammer the server. Interviewers ask this to see whether we understand why some stages need memory and others do not, and whether we fix the cause rather than the symptom. In this answer, we will recap streaming and blocking stages, reproduce the failure, look at what allowDiskUse does, and then go through the real fixes: filtering early, pre-aggregation with $merge, and replacing $unwind plus $group with array operators.
1A Quick Recap: Streaming and Blocking Stages
Most pipeline stages stream: $match, $project, $addFields and $unwind look at one document at a time and pass results on immediately, so they need almost no memory. Some stages are blocking: they cannot produce any output until they have seen all their input. $group must see every document before it knows each group's final total. $sort must see every document before it knows which comes first. $bucket, $setWindowFields and $facet have similar needs.
Blocking stages keep their working data in memory, and MongoDB limits how much each one may use, traditionally 100 MB per stage. The limit protects the server: without it, one careless pipeline could take all the memory needed by other queries.
| Stage | Kind | Memory grows with |
|---|---|---|
$match, $project, $addFields | streaming | nothing, one document at a time |
| $unwind | streaming | nothing, but multiplies documents downstream |
| $group | blocking | number of groups and size of accumulators |
| $sort without index | blocking | all input documents |
| $sort + $limit n | blocking, bounded | only n documents |
$group with $push or $addToSet | blocking | every value pushed into the arrays |
2Reproducing the Failure
Here is a pipeline that groups three years of order lines by product.
There are two growth problems here. The $unwind turns 10 million orders into 60 million line documents, all of which flow into $group. And $addToSet keeps a set of customer ids for each SKU, so popular products accumulate hundreds of thousands of values each. The group's memory grows with both the number of groups and the size of each group's accumulators, and it crosses 100 MB.
3What allowDiskUse Does, and What It Does Not
With allowDiskUse: true, a blocking stage that runs out of memory writes partial results to temporary files on disk and merges them later. Since MongoDB 6.0, the server parameter allowDiskUseByDefault is true, so pipelines spill unless we pass allowDiskUse: false; in older versions the default was false and the pipeline failed. Check your version and any platform settings, because some managed tiers restrict disk use.
Spilling is a safety valve, not a fix. Disk is much slower than memory, temporary files use disk space on the node, and a pipeline that spills is usually reading far more data than it needs. There are also limits it cannot lift. A single output document still cannot exceed 16 MB, so a $push that builds a huge array in one group fails regardless. So we treat a spill as a sign to redesign.
4Fix 1: Reduce the Data Early
The cheapest memory is memory we never use. We put $match first so only relevant documents enter the pipeline, and $project early so only the fields we need are carried along. When the first stage is a $match or $sort on indexed fields, MongoDB uses the index and reads far less.
Notice that we also changed the question. Do we really need the set of every buyer per SKU, or just the count of buyers? A distinct count over huge sets is better computed by a separate group step, grouping first by SKU and customer and then by SKU, which keeps one small document per pair instead of a giant array, or by an approximate method in an analytics system.
5Fix 2: Pre-Aggregate With $merge
If a dashboard needs totals over all history, computing them from raw orders on every request is wasteful. Instead, a scheduled job aggregates only new data and merges it into a summary collection.
Each run processes one hour of data, so its memory need stays small no matter how much history exists. The whenMatched pipeline adds the new hour's quantity to the existing daily total. The job must record lastRun reliably and handle late-arriving orders, for example by re-aggregating the last few hours, but in return the dashboard reads a few hundred small rows.
6Fix 3: Use Array Operators Instead of $unwind and $group
A common pattern is to $unwind an array and then $group back by the original _id just to compute something per document, such as the number of lines or the order total. That multiplies the documents only to collapse them again. Array expression operators do the same work inside each document, streaming, with no blocking stage at all.
$size counts the elements, $reduce folds the array into a single value, and $filter or $map handle other cases. The result is the same, the pipeline streams, and memory stays flat.
7Follow-up questions
Does the 100 MB limit apply to the whole pipeline?
It applies per blocking stage, not to the whole pipeline. A pipeline with two $group stages can use up to the limit in each. Check your version's documentation, because the limits are server parameters and newer versions describe them in more detail.
Can $lookup run out of memory too?
$lookup itself streams the outer documents, but the joined array for each document is part of that document, so a lookup that matches thousands of documents can push an output document toward the 16 MB limit. Using a pipeline inside $lookup with $match and $project keeps the joined part small.
When should this move to a separate analytics system?
When the pipelines scan most of the data every time, need many joins, or compete with production traffic. Streaming changes to a warehouse and running such reports there keeps the operational database fast.
8Conclusion
In this answer, we saw that streaming stages need almost no memory while blocking stages such as $group and $sort hold their working data and are limited per stage, traditionally to 100 MB. allowDiskUse, on by default in recent versions, lets them spill to disk, but it is a slow safety valve and cannot lift the 16 MB document limit. The real fixes are to filter and project early with indexes on the first stages, to pre-aggregate incrementally with $merge into a summary collection, and to replace $unwind followed by $group with array operators such as $size and $reduce.
Open with
The error comes from blocking stages. Most stages, like match and project, stream one document at a time, but group and sort must see all their input before producing output, so they hold data in memory, and each blocking stage has a limit, traditionally a hundred megabytes.
Then, if they want more
When a stage exceeds it, the pipeline fails unless it can spill to temporary files with allowDiskUse. From 6.0 that is allowed by default, but it depends on the version and the platform.
I see spilling as a safety valve rather than a fix, because it is slow and it cannot get around the sixteen megabyte limit on a single document, for example a push that builds a huge array.
My fixes, in order: reduce data early with a match first, ideally on an indexed field, and a project to drop unneeded fields, and question accumulators like addToSet that grow without bound.
If the same aggregation over all history runs repeatedly, pre-aggregate on a schedule: process only new data and merge it into a summary collection with $merge, so each run is small.
And if a pipeline unwinds an array only to group it back by the same document, replace that with size, reduce, filter or map inside each document, so nothing blocks.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- MongoDB manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "An aggregation pipeline fails with an error that a stage exceeded its memory limit....": https://scrivio-interview-library.netlify.app/databases/mongodb/796de74d18/