mongodb - 使用组数获取 $group 结果

标签 mongodb mongodb-query aggregation-framework

假设我有一个名为“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 限制。此外,执行相同的查询只是为了获得计数似乎是一种浪费。

那么可以同时获取文档结果和计数吗?任何帮助表示赞赏。

最佳答案

  1. 使用$projecttagcount存入tmp
  2. 使用 $pushaddToSettmp 存储到您的 data 列表中。

代码:

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
}

关于mongodb - 使用组数获取 $group 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13529323/

相关文章:

mongodb - 你如何否定 mongodb 中的 $match 聚合

java - $set 不会更改 mongodb 的 java 驱动程序中字段的值

database - MongoDB 每秒可以发生多少个事务?

mongodb - MongoDB 中的条件更新

node.js - Mongodb 排序返回未定义

javascript - 不明确的意外标识符错误

node.js - mongodb聚合: average and sorting

node.js - 如何在mongodb中过滤两次之间的数据

mongodb - 选择一个包含元素数量有限的数组的文档

node.js - 如何查询 mongodb 以查找包含另一个数组中两个元素的数组