就 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/