On this page本页内容
$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.采用正整数,指定要传递的最大文档数。
Starting 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位整数限制。传递到管道的值超过此限制将返回无效参数错误。
$limit
If using the 如果将$limit
stage with any of:$limit
阶段与以下任何一项一起使用:
$sort
aggregation stage,$sort
聚合阶段,sort()
method, orsort()
方法,或sort
field to the findAndModify
command or the findAndModify()
shell method,findAndModify
命令或findAndModify()
shell方法的sort
字段,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:有关每种类型的更多信息,请参阅以下内容:
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.对其传递的文档的内容没有影响。
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
之前,并且没有修改文档数量的中间阶段时,优化器可以将$limits
合并到$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
项超过聚合内存限制时,此优化仍然适用。