Docs HomeMongoDB Manual

$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 64-bit integer> }

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

Note

Starting in MongoDB 5.0, the $limit pipeline aggregation has a 64-bit integer limit. Values passed to the pipeline which exceed this limit will return a invalid argument error.从MongoDB 5.0开始,$limit管道聚合有一个64位整数限制。传递给管道的值超过此限制将返回一个无效的参数错误。

Behavior行为

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

If using the $limit stage with any of:如果将$limit阶段与以下任一项一起使用:

be sure to include at least one field in your sort that contains unique values, before passing results to the $limit stage.在将结果传递到$limit阶段之前,请确保在排序中至少包含一个包含唯一值的字段。

Sorting on fields that contain duplicate values may return an inconsistent sort order for those duplicate fields over multiple executions, especially when the collection is actively receiving writes.对包含重复值的字段进行排序可能会在多次执行中为这些重复字段返回不一致的排序顺序,尤其是当集合正在主动接收写入时。

The easiest way to guarantee sort consistency is to include the _id field in your sort query.保证排序一致性的最简单方法是在排序查询中包含_id字段。

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.allowDiskUsetrue并且n个项目超过聚合内存限制时,此优化仍然适用。