首页 文章

将值转换为mongodb聚合中的键

提问于
浏览
1

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

我想要的是返回单个文档,使用新自动创建的字段,其中每个字段都被命名为唯一的$ group _id值,并且此值应该

由document组成,$ group返回特定的_id值 .

For example for collection
Books: 

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

aggregation pipeline like that

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


    returns 2 documents with structure 

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

But i would like to receive single document with structure:

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

In simple words, i want to use $group _id
 property as new field in resulting document,
 and proper $group values for specific _id must be value of new variable.

If somebody faced with such a queries,
 please, assist with that or give some clues how to solve it.
Thanks in advance.

1 回答

  • 1

    您可以尝试以下聚合

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

相关问题