假设我有一个名为“posts”的集合(实际上它是一个更复杂的集合,posts 太简单了),其结构如下:
> db.posts.find()
{ "_id" : ObjectId("50ad8d451d41c8fc58000003"), "title" : "Lorem ipsum", "author" :
"John Doe", "content" : "This is the content", "tags" : [ "SOME", "RANDOM", "TAGS" ] }
我希望这个集合跨越数十万甚至数百万,我需要按标签查询帖子并按标签对结果进行分组并显示分页的结果。这就是聚合框架的用武之地。我打算使用 aggregate() 方法来查询集合:
db.posts.aggregate([
{ "$unwind" : "$tags" },
{ "$group" : {
_id: { tag: "$tags" },
count: { $sum: 1 }
} }
]);
关键是要创建分页器,我需要知道输出数组的长度。我知道要做到这一点,你可以这样做:
db.posts.aggregate([
{ "$unwind" : "$tags" },
{ "$group" : {
_id: { tag: "$tags" },
count: { $sum: 1 }
} }
{ "$group" : {
_id: null,
total: { $sum: 1 }
} }
]);
但这会丢弃前一个管道(第一组)的输出。有没有办法在保留每个管道的输出的同时组合这两个操作?我知道整个聚合操作的输出可以转换为某种语言的数组并计算内容,但管道输出可能超过 16Mb 限制。此外,执行相同的查询只是为了获得计数似乎是一种浪费。
那么是否可以同时获取文档结果和计数呢?任何帮助表示赞赏。