$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.采用一个正整数,该整数指定要传递的最大文档数。NoteStarting in MongoDB 5.0, the从MongoDB 5.0开始,$limit
pipeline aggregation has a 64-bit integer limit. Values passed to the pipeline which exceed this limit will return a invalid argument error.$limit
管道聚合有一个64位整数限制。传递给管道的值超过此限制将返回一个无效的参数错误。
Behavior行为
Using $limit with Sorted Results对排序结果使用$limit
If using the 如果将$limit
stage with any of:$limit
阶段与以下任一项一起使用:
the$sort
aggregation stage,$sort
聚合阶段,thesort()
method, orsort()
方法,或者thesort
field to thefindAndModify
command or thefindAndModify()
shell method,findAndModify
命令或findAndModify()
shell方法的排序字段,
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
对它传递的文档的内容没有影响。
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.allowDiskUse
为true
并且n
个项目超过聚合内存限制时,此优化仍然适用。