我有一组文档,每个文档都包含一个(简单的)文档数组。我想使用聚合管道将嵌入的文档(“成果”)移动到父文档,如下面的示例所示。注意,"name“值将成为父文档中的键。
我看过Mongo的聚合框架(特别是$project
、$replaceRoot
、$arrayToObject
),但没有取得任何进展。
我想转换一下这个
{
"_id" : 3258,
"fruits" : [
{
"name" : "apple",
"quantity" : 2
},
{
"name" : "banana",
"quantity" : 86
},
{
"name" : "orange",
"quantity" : 4
},
{
"name" : "pineapple",
"quantity" : 28
},
{
"name" : "strawberry",
"quantity" : 193
}
]
}
到这个
{
"_id" : 3258,
"apple" : 2,
"banana" : 86,
"orange" : 4,
"pineapple" : 28,
"strawberry": 193
}
发布于 2019-08-10 19:52:08
您需要$replaceRoot和$mergeObjects来创建一个包含_id
和其他字段的新文档根。还可以运行$arrayToObject将数组转换为单个文档,尝试:
db.collection.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{ _id: "$_id" },
{ $arrayToObject: { $map: { input: "$fruits", in: [ "$$this.name", "$$this.quantity" ] } } }
]
}
}
}
])
https://stackoverflow.com/questions/57446595
复制相似问题