- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $limit (aggregation)
$limit (aggregation)¶
On this page
Definition¶
Example¶
Consider the following example:
This operation returns only the first 5 documents passed to it
by the pipeline. $limit
has no effect on the content
of the documents it passes.
Note
When a $sort
precedes a $limit
and there are no
intervening stages that modify the number of documents, the optimizer can
coalesce the $limit
into the $sort
. This allows
the $sort
operation to only
maintain the top n
results as it progresses, where n
is the
specified limit, and ensures that MongoDB only needs to store n
items in memory.
This optimization still applies when allowDiskUse
is true
and
the n
items exceed the aggregation memory limit.