$limit (aggregation)

Definition

  • $limit
  • Limits the number of documents passed to the next stage in thepipeline.

The $limit stage has the following prototype form:

  1. { $limit: <positive integer> }

$limit takes a positive integer that specifies themaximum number of documents to pass along.

Example

Consider the following example:

  1. db.article.aggregate(
  2. { $limit : 5 }
  3. );

This operation returns only the first 5 documents passed to itby the pipeline. $limit has no effect on the contentof the documents it passes.

Note

When a $sort precedes a $limit and there are nointervening stages that modify the number of documents, the optimizer cancoalesce the $limit into the $sort. This allowsthe $sort operation to onlymaintain the top n results as it progresses, where n is thespecified limit, and ensures that MongoDB only needs to store n items in memory.This optimization still applies when allowDiskUse is true andthe n items exceed the aggregation memory limit.

See also

Aggregation with the Zip Code Data Set,Aggregation with User Preference Data