使用组计数获取 $group 结果 [英] Obtaining $group result with group count
问题描述
假设我有一个名为posts"的集合(实际上它是一个更复杂的集合,posts 太简单了),其结构如下:
Assuming I have a collection called "posts" (in reality it is a more complex collection, posts is too simple) with the following structure:
> db.posts.find()
{ "_id" : ObjectId("50ad8d451d41c8fc58000003"), "title" : "Lorem ipsum", "author" :
"John Doe", "content" : "This is the content", "tags" : [ "SOME", "RANDOM", "TAGS" ] }
我希望这个集合可以跨越数十万甚至数百万,我需要按标签查询帖子并按标签对结果进行分组并显示分页的结果.这就是聚合框架的用武之地.我打算使用aggregate() 方法来查询集合:
I expect this collection to span hundreds of thousands, perhaps millions, that I need to query for posts by tags and group the results by tag and display the results paginated. This is where the aggregation framework comes in. I plan to use the aggregate() method to query the collection:
db.posts.aggregate([
{ "$unwind" : "$tags" },
{ "$group" : {
_id: { tag: "$tags" },
count: { $sum: 1 }
} }
]);
问题是要创建分页器,我需要知道输出数组的长度.我知道你可以这样做:
The catch is that to create the paginator I would need to know the length of the output array. I know that to do that you can do:
db.posts.aggregate([
{ "$unwind" : "$tags" },
{ "$group" : {
_id: { tag: "$tags" },
count: { $sum: 1 }
} }
{ "$group" : {
_id: null,
total: { $sum: 1 }
} }
]);
但这会丢弃前一个管道(第一组)的输出.有没有办法在保留每个管道输出的同时将两个操作结合起来?我知道整个聚合操作的输出可以转换为某种语言的数组并计算内容,但管道输出可能会超过 16Mb 的限制.此外,执行相同的查询只是为了获得计数似乎是一种浪费.
But that would discard the output from previous pipeline (the first group). Is there a way that the two operations be combined while preserving each pipeline's output? I know that the output of the whole aggregate operation can be cast to an array in some language and have the contents counted but there may be a possibility that the pipeline output may exceed the 16Mb limit. Also, performing the same query just to obtain the count seems like a waste.
那么可以同时获取文档结果和计数吗?任何帮助表示赞赏.
So is obtaining the document result and count at the same time possible? Any help is appreciated.
推荐答案
- 使用
$project
将tag
和count
保存到tmp
- 使用
$push
或addToSet
将tmp
存储到您的data
列表中.
- Use
$project
to savetag
andcount
intotmp
- Use
$push
oraddToSet
to storetmp
into yourdata
list.
代码:
db.test.aggregate(
{$unwind: '$tags'},
{$group:{_id: '$tags', count:{$sum:1}}},
{$project:{tmp:{tag:'$_id', count:'$count'}}},
{$group:{_id:null, total:{$sum:1}, data:{$addToSet:'$tmp'}}}
)
输出:
{
"result" : [
{
"_id" : null,
"total" : 5,
"data" : [
{
"tag" : "SOME",
"count" : 1
},
{
"tag" : "RANDOM",
"count" : 2
},
{
"tag" : "TAGS1",
"count" : 1
},
{
"tag" : "TAGS",
"count" : 1
},
{
"tag" : "SOME1",
"count" : 1
}
]
}
],
"ok" : 1
}
这篇关于使用组计数获取 $group 结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!