Mongodb 如何在聚合中的对象数组上使用$map?

Mongodb 如何在聚合中的对象数组上使用$map?,mongodb,aggregation-framework,Mongodb,Aggregation Framework,给定以下示例集合: { _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_b

给定以下示例集合:

{ _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。在这两种情况下,我都无法实现向根文档添加动态键和从嵌入文档中提取“value”字段的组合

您需要使用双美元符号来引用变量,例如:

{
    $replaceRoot: {
        newRoot: {
            $mergeObjects: [
                { _id: "$_id", name: "$name" },
                {
                    $arrayToObject: {
                        $map: {
                            input: { $objectToArray: "$attribute_bag" },
                            in: [ "$$this.k", "$$this.v.value" ]
                        }
                    }
                }
            ]
        }
    }
}