我有這樣的檔案:
[
{
title: 'apple',
attributes: {
colour: 'red',
kind: 'fruit'
},
{
title: 'broccoli',
attributes: {
colour: 'green',
kind: 'vegetable'
}
},
]
在我的聚合管道中,我想從本質上將層次結構展平一層,使其看起來像這樣:
[
{
title: 'apple',
colour: 'red',
kind: 'fruit'
},
{
title: 'broccoli',
colour: 'green',
kind: 'vegetable'
}
]
問題是,嵌套物件中的鍵在檔案中是動態的,所以我不能$project靜態地使用它們。我需要動態地將這些嵌套的鍵/值對拉到頂部物件。
uj5u.com熱心網友回復:
使用聚合框架可能是這樣的:
db.collection.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$$ROOT",
"$attributes"
]
}
}
},
{
$project: {
attributes: 0
}
}
])
解釋:
- ReplaceRoot 與根物件和屬性之間的合并物件
- 從輸出中洗掉屬性物件。
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470248.html
