gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:42:03 27 4
gpt4 key购买 nike

鉴于以下示例集合:

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

最佳答案

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

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

Mongo Playground

关于mongodb - 如何在聚合中的对象数组上使用 $map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62283498/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com