- Reference >
- Operators >
- Aggregation Framework Operators >
- Pipeline Aggregation Operators >
- $limit (aggregation)
$limit (aggregation)¶
-
$limit¶ Restricts the number of documents that pass through the
$limitin the pipeline.$limittakes a single numeric (positive whole number) value as a parameter. Once the specified number of documents pass through the pipeline operator, no more will. Consider the following example:This operation returns only the first 5 documents passed to it from by the pipeline.
$limithas no effect on the content of the documents it passes.Note
Changed in version 2.4:
$sortand memory requirements:- When a
$sortimmediately precedes a$limitin the pipeline, the$sortoperation only maintains the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store the number of items specified by$limitin memory. Before MongoDB 2.4,$sortwould sort all the results in memory, and then limit the results to n results. - Unless the
$sortoperator can use an index or immediately precedes a$limit, the$sortoperation must fit within memory. Before MongoDB 2.4, unless the$sortoperator can use an index, the$sortoperation must fit within memory.
$sortproduces an error if the operation consumes 10 percent or more of RAM.- When a