mongodb - 将 mongodb 聚合中的值转换为键

标签 mongodb mongodb-query aggregation-framework

就 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 值必须是新变量的值。

如果有人遇到这样的疑问,请协助解决或提供一些解决问题的线索。提前致谢。

最佳答案

您可以尝试以下聚合

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

关于mongodb - 将 mongodb 聚合中的值转换为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52739057/

相关文章:

node.js - Mongoose:根据查询动态添加某些参数的验证器

java - 无法包含带有 Spring 数据聚合的嵌套字段

arrays - 查询 MongoDB 中的整个对象数组

java - Spring MongoDB : Criteria methods non-static access

node.js - 如何在 mongodb 的 typeorm 中使用 “OR” 运算符

mongodb-query - 如何将MongoDB集合变成 'Table'

node.js - 在数组中的对象中按日期搜索

node.js - 如何使用 $filter(aggregation) 仅在条件为 true 时选择数组的某些字段?

mongodb - $concatArrays 不适用于现有的多数组字段

java - MongoDB Morphia 表示已弃用