$limit (aggregation)

On this page本页内容

Definition定义

$limit

Limits the number of documents passed to the next stage in the pipeline.限制传递到管道中下一阶段的文档数量。

The $limit stage has the following prototype form:$limit阶段的原型形式如下:

{ $limit: <positive integer> }

$limit takes a positive integer that specifies the maximum number of documents to pass along.接受一个正整数,该整数指定要传递的最大文档数。

Behavior行为

Using $limit with Sorted Results对排序结果使用$limit

If using the $limit stage with any of:如果将$limit阶段用于以下任何一种情况:

be sure that you are performing a stable sort before passing results to the $limit stage. 在将结果传递到$limit阶段之前,确保正在执行稳定排序A stable sort ensures that the sort order of returned documents remains the same across multiple executions of the same sort; especially important when used with the $limit stage.稳定的排序可确保在多次执行相同排序时,返回文档的排序顺序保持不变;与$limit阶段一起使用时尤其重要。

See the following for more information on each:有关每种方法的更多信息,请参阅以下内容:

Example示例

Consider the following example:考虑下面的例子:

db.article.aggregate([
   { $limit : 5 }
]);

This operation returns only the first 5 documents passed to it by the pipeline. 此操作仅返回管道传递给它的前5个文档。$limit has no effect on the content of the documents it passes.$limit对通过的文档内容没有影响。

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. $sort先于$limit,并且没有修改文档数量的中间阶段时,优化器可以将$limit合并到$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. 这允许$sort操作在进行时只维护前n个结果,其中n是指定的限制,并确保MongoDB只需要在内存中存储n个项。This optimization still applies when allowDiskUse is true and the n items exceed the aggregation memory limit.allowDiskUsetruen项超过聚合内存限制时,此优化仍然适用。