On this page本页内容
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 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:有关每种方法的更多信息,请参阅以下内容:
Consider the following example:考虑下面的例子:
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.allowDiskUse为true且n项超过聚合内存限制时,此优化仍然适用。