MongoDB聚合的有效分页? [英] Efficient pagination of MongoDB aggregation?
问题描述
为了提高效率,Mongo文档建议limit语句紧跟在sort语句之后,因此最终有些荒谬:
For efficiency, the Mongo documentation recommends that limit statements immediately follow sort statements, thus ending up with the somewhat nonsensical:
collection.find(f).sort(s).limit(l).skip(p)
我说这有点荒谬,因为它似乎说拿了前l个项目,然后删除了这些l中的第一个p.由于p通常大于l,因此您会以为最终没有结果,但实际上,您最终会得到l个结果.
I say this is somewhat nonsensical because it seems to say take the first l items, and then drop the first p of those l. Since p is usually larger than l, you'd think you'd end up with no results, but in practice you end up with l results.
聚合可以按您期望的那样工作:
Aggregation works more as you'd expect:
collection.aggregate({$unwind: u}, {$group: g},{$match: f}, {$sort: s}, {$limit: l}, {$skip: p})
如果p> = l,则返回0个结果.
returns 0 results if p>=l.
collection.aggregate({$unwind: u}, {$group: g}, {$match: f}, {$sort: s}, {$skip: p}, {$limit: l})
有效,但是文档似乎暗示如果匹配返回的结果集大于工作内存,则此操作将失败.这是真的?如果是这样,是否有更好的方法对通过聚合返回的结果集执行分页?
works, but the documentation seems to imply that this will fail if the match returns a result set that's larger than working memory. Is this true? If so, is there a better way to perform pagination on a result set returned through aggregation?
Source: the "Changed in version 2.4" comment at the end of this page: http://docs.mongodb.org/manual/reference/operator/aggregation/sort/
推荐答案
在MongoDB游标方法中(例如,当使用find()
时),可以按任何顺序=>顺序应用limit
,sort
,skip
不要紧. find()
返回一个游标,在其上应用了修改.排序总是在限制之前完成,跳过也要在限制之前完成.因此换句话说,顺序为:排序->跳过->限制.
In MongoDB cursor methods (i.e. when using find()
) like limit
, sort
, skip
can be applied in any order => order does not matter. A find()
returns a cursor on which modifications applied. Sort is always done before limit, skip is done before limit as well. So in other words the order is: sort -> skip -> limit.
聚合框架不返回数据库游标.而是返回带有汇总结果的 document .它的工作原理是在流水线的每个步骤中产生中间结果,因此操作顺序确实很重要.
Aggregation framework does not return a DB cursor. Instead it returns a document with results of aggregation. It works by producing intermediate results at each step of the pipeline and thus the order of operations really matters.
我猜MongoDB不支持光标修改器方法的顺序,因为它是在内部实现的方式.
I guess MongoDB does not support order for cursor modifier methods because of the way it's implemented internally.
您无法对聚合框架的结果进行分页,因为只有一个文档仅包含结果.您仍然可以使用跳过和限制对常规查询进行分页,但是更好的做法是使用范围查询,因为它使用索引的效率很高.
You can't paginate on a result of aggregation framework because there is a single document with results only. You can still paginate on a regular query by using skip and limit, but a better practice would be to use a range query due to it's efficiency of using an index.
更新:
由于v2.6 Mongo聚合框架返回了游标而不是单个文档.比较: v2.4 和 v2.6 .
Since v2.6 Mongo aggregation framework returns a cursor instead of a single document. Compare: v2.4 and v2.6.
这篇关于MongoDB聚合的有效分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!