我有这样的文件:
[
{
title: 'apple',
attributes: {
colour: 'red',
kind: 'fruit'
},
{
title: 'broccoli',
attributes: {
colour: 'green',
kind: 'vegetable'
}
},
]
Run Code Online (Sandbox Code Playgroud)
在我的聚合管道中,我想从本质上将层次结构扁平化一层深,如下所示:
[
{
title: 'apple',
colour: 'red',
kind: 'fruit'
},
{
title: 'broccoli',
colour: 'green',
kind: 'vegetable'
}
]
Run Code Online (Sandbox Code Playgroud)
问题是,嵌套对象中的键在文档中是动态的,因此我无法$project静态地使用它们。我需要动态地将这些嵌套的键/值对拉到顶部对象。
也许使用聚合框架是这样的:
db.collection.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$$ROOT",
"$attributes"
]
}
}
},
{
$project: {
attributes: 0
}
}
])
Run Code Online (Sandbox Code Playgroud)
解释:
| 归档时间: |
|
| 查看次数: |
702 次 |
| 最近记录: |