> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# Aggregation Pipeline Limits

Aggregation operations with the [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) command have the following limitations.

## Result Size Restrictions

The [`aggregate`](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#mongodb-dbcommand-dbcmd.aggregate) command can either return a cursor or store the results in a collection. Each document in the result set is subject to the 16 mebibyte [BSON Document Size limit](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-BSON-Document-Size). If any single document exceeds the [BSON Document Size limit](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-BSON-Document-Size), the aggregation produces an error. The limit only applies to the returned documents. During the pipeline processing, the documents may exceed this size. The [`db.collection.aggregate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#mongodb-method-db.collection.aggregate) method returns a cursor by default.

## Number of Stages Restrictions

MongoDB limits the number of [aggregation pipeline stages](https://www.mongodb.com/docs/manual/reference/mql/aggregation-stages.md#std-label-aggregation-pipeline-operator-reference) allowed in a single pipeline to 1000.

If an aggregation pipeline exceeds the stage limit before or after being parsed, you receive an error.

## Memory Restrictions

Starting in MongoDB 6.0, the [`allowDiskUseByDefault`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.allowDiskUseByDefault) parameter controls whether pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default.

- If [`allowDiskUseByDefault`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.allowDiskUseByDefault) is set to `true`, pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default. You can disable writing temporary files to disk for specific `find` or `aggregate` commands using the `{ allowDiskUse: false }` option.

- If [`allowDiskUseByDefault`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.allowDiskUseByDefault) is set to `false`, pipeline stages that require more than 100 megabytes of memory to execute raise an error by default. You can enable writing temporary files to disk for specific `find` or `aggregate` using the `{ allowDiskUse: true }` option.

The [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) aggregation stage is not restricted to 100 megabytes of RAM because it runs in a separate process.

Examples of stages that can write temporary files to disk when [allowDiskUse](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#std-label-aggregate-cmd-allowDiskUse) is `true` are:

- [`$bucket`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#mongodb-pipeline-pipe.-bucket)

- [`$bucketAuto`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketauto.md#mongodb-pipeline-pipe.-bucketAuto)

- [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group)

- [`$setWindowFields`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/setwindowfields.md#mongodb-pipeline-pipe.-setWindowFields)

- [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) when the sort operation is not supported by an index

- [`$sortByCount`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortbycount.md#mongodb-pipeline-pipe.-sortByCount)

**Note:**

Pipeline stages operate on streams of documents with each pipeline stage taking in documents, processing them, and then outputting the resulting documents.

Some stages can't output any documents until they have processed all incoming documents. These pipeline stages must keep their stage output in RAM until all incoming documents are processed. As a result, these pipeline stages may require more space than the 100 MB limit.

If the results of one of your [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) pipeline stages exceed the limit, consider [adding a $limit stage.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#std-label-sort-limit-sequence)

In addition to the per-stage limit, a single operation can use no more memory than the [per-operation memory limit.](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#std-label-operation-memory-limit)

The [profiler log messages](https://www.mongodb.com/docs/manual/tutorial/manage-the-database-profiler.md#std-label-database-profiler) and [diagnostic log messages](https://www.mongodb.com/docs/manual/reference/log-messages.md#std-label-log-messages-ref) includes a `usedDisk` indicator if any aggregation stage wrote data to temporary files due to [memory restrictions.](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#std-label-agg-memory-restrictions)

## Per-Operation Memory Limit

Starting in MongoDB 9.0, MongoDB limits the total amount of memory that a single query operation can use. The limit applies to the combined memory of all memory-tracked stages of the operation.

Tracked memory includes:

- Blocking stages such as [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) and [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort)

- Expression evaluation

- Query execution stages that buffer records, such as geospatial proximity searches, counts that use an index, and updates

By default, the limit is 1 gigabyte or 20% of the memory available to the server process, whichever is greater. MongoDB sets the default when the server starts.

To change the per-operation limit, set the [`internalQueryMaxMemoryUsageBytesPerOperation`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.internalQueryMaxMemoryUsageBytesPerOperation) parameter at startup, at runtime, or with query settings.

For memory-intensive expressions that the per-operation limit does not cover, MongoDB applies a limit on the maximum memory that a subset of expressions can use. The default of this limit is 100 megabytes. To change this limit, set the [`internalQueryMaxSingleExpressionMemoryUsageBytes`](https://www.mongodb.com/docs/manual/reference/parameters.md#mongodb-parameter-param.internalQueryMaxSingleExpressionMemoryUsageBytes) parameter at startup or at runtime.

The per-operation limit is separate from the 100 megabyte per-stage memory limit and doesn't change how stages spill to disk. To learn about the per-stage limit, see [Memory Restrictions.](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#std-label-agg-memory-restrictions)

If an operation exceeds the per-operation limit, MongoDB ends the operation and returns one of the following errors:

- [`QueryExceededMemoryLimitNoDiskUseAllowed`](https://www.mongodb.com/docs/manual/reference/error-codes.md#mongodb-error-292) when a stage that can spill to disk exceeds the limit and `allowDiskUse` is `false`. Run the operation with `{ allowDiskUse: true }` so that the stage spills to disk instead of failing.

- [`ExceededMemoryLimit`](https://www.mongodb.com/docs/manual/reference/error-codes.md#mongodb-error-146) for other operations that exceed the limit.

Most operations use much less memory than the limit. If an operation returns a memory limit error, reduce the memory that the operation requires by performing one or more of the following actions:

- Use an index to satisfy the sort so that MongoDB doesn't sort documents in memory. To learn more, see [Sort and Index Use.](https://www.mongodb.com/docs/manual/reference/method/cursor.sort.md#std-label-sort-index-use)

- Add a [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) stage after a [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) stage so that the sort keeps only the documents you need. To learn more, see [$sort and $limit Memory Optimization.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#std-label-sort-limit-sequence)

- Filter documents with [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) as early as possible in the pipeline so that later stages process fewer documents. To learn more, see [Aggregation Pipeline Optimization.](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#std-label-agg-pipeline-optimization)

To check per-operation memory usage, use these [`serverStatus`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-dbcommand-dbcmd.serverStatus) metrics:

- [`metrics.query.peakMemoryUsageOperation`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.query.peakMemoryUsageOperation)

- [`metrics.query.operationsFailedDueToMemoryLimit`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.query.operationsFailedDueToMemoryLimit)

- [`metrics.query.configuredMaxMemoryUsageBytesPerOperation`](https://www.mongodb.com/docs/manual/reference/command/serverstatus.md#mongodb-serverstatus-serverstatus.metrics.query.configuredMaxMemoryUsageBytesPerOperation)
