【问题标题】:Convert values to keys in mongodb aggregation将值转换为 mongodb 聚合中的键
【发布时间】:2019-03-15 07:06:39
【问题描述】:

就 MongoDB 在聚合管道中提供 $group 方法而言,它返回文档列表,其中 _id 保留一些“不同”的分组值,其他字段保留文档数组,按给定条件分组。

我想要的是返回一个文档,其中属性是聚合的结果。

示例集合:

{author: "Author1", title: "Title1"}
{author: "Author2", title: "Title2"}
{author: "Author2", title: "Title3"}

聚合

db.getCollection('books').aggregate([ 
    {"$group": {
           _id: "$author",
           books: { $push: "$$ROOT" }
          }
    }
])

这给了我以下输出:

{_id: 'Author1', books: [{author: "Author1", title: "Title1"}]},
{_id: 'Author2', books: [{author: "Author2", title: "Title2"}, {author: "Author2", title: "Title3"}]}

但我希望将结果作为一个单一的对象获得,如下所示:

{
  Author1: [
    {author: "Author1", title: "Title1"}
  ],
  Author2: [ 
    {author: "Author2", title: "Title2"},
    {author: "Author2", title: "Title3"}
  ]
}

简单来说,我想在结果文档中使用_id 属性作为新字段,并且特定_id 的正确$group 值必须是新变量的值。

如果有人遇到此类问题,请提供帮助或提供一些解决方法的线索。提前致谢。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你可以试试下面的聚合

    db.getCollection('books').aggregate([ 
      { "$group": {
        "_id": "$author",
        "books": { "$push": "$$ROOT" }
      }},
      { "$group": {
        "_id": null,
        "data": {
          "$push": { "k": "$_id", "v": "$books" }
        }
      }},
      { "$replaceRoot": {
        "newRoot": { "$arrayToObject": "$data" }
      }}
    ])
    

    【讨论】:

      猜你喜欢
      • 2019-08-09
      • 2022-01-22
      • 1970-01-01
      • 2021-11-25
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      相关资源
      最近更新 更多