我有以下记录:
id: 119,
customfields: Array (2)
0: Object
value: "Mr"
type: "salutation"
1: Object
value: "Google"
type: "company"
我需要更新此文档以便我得到:
id: 119,
salutation: "Mr",
company: "Google"
重要的是:
salutation
,其他记录具有 company
,而其他记录可能具有其他无关紧要的字段。salutation
数组内没有 customfields
记录,因此应被忽略。公司的逻辑也一样。$map
customfields
到 k-v 元组数组。然后, $mergeObjects
与 $$ROOT
对象得到最终对象。 $unset
现在无用的自定义字段和 $merge
通过 id
更新回文档。
db.collection.aggregate([
{
"$match": {
"id": 119
}
},
{
"$set": {
"customfields": {
"$arrayToObject": {
"$map": {
"input": "$customfields",
"as": "cf",
"in": {
"k": "$$cf.type",
"v": "$$cf.value"
}
}
}
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$mergeObjects": [
"$$ROOT",
"$customfields"
]
}
}
},
{
"$unset": "customfields"
},
{
"$merge": {
"into": "collection",
"on": "id"
}
}
])
这是另一种方法,使用
"$reduce"
重建文档。
db.collection.update({
"id": 119
},
[
{
"$set": {
"newRoot": {
"$reduce": {
"input": "$customfields",
"initialValue": {
"id": "$id"
},
"in": {
"$mergeObjects": [
"$$value",
{
"$arrayToObject": [
[
{
"k": "$$this.type",
"v": "$$this.value"
}
]
]
}
]
}
}
}
}
},
{"$replaceWith": "$newRoot"}
])
在 mongoplayground.net 上尝试一下。