给出以下示例集合:
{ _id: 1, name: 'One', attribute_bag: { lights: { type: 'basic', value: '8' }, doors: { type: 'basic', value: '7' } } }
{ _id: 2, name: 'Two', attribute_bag: { switches: { type: 'basic', value: '2' } } }
{ _id: 3, name: 'Three', attribute_bag: { windows: { type: 'basic', value: '8' }, color: { type: 'descriptive', value: 'blue' } } }
我一直试图结束以下内容:
{ _id: 1, name: 'One', lights: '8', doors: '7' }
{ _id: 2, name: 'Two', switches: '2' }
{ _id: 3, name: 'Three', windows: '8', color: 'blue' }
使用我尝试过的聚合框架:
$replaceRoot: {
newRoot: {
$arrayToObject: {
$map: {
input: {$objectToArray: "$attribute_bag"},
as: "attribute",
in: ["$attribute.k", "$attribute.v.value"],
// alternatively {k: $attribute.k, v: $attribute.v}
}
}
}
}
并使用$ addFields + $ unwind + $ group。在这两种情况下,我都无法完成将动态键添加到根文档以及将“值”字段从嵌入式文档中拉出的组合。
答案 0 :(得分:2)
您需要使用双美元符号来引用一个变量,工作示例:
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{ _id: "$_id", name: "$name" },
{
$arrayToObject: {
$map: {
input: { $objectToArray: "$attribute_bag" },
in: [ "$$this.k", "$$this.v.value" ]
}
}
}
]
}
}
}