In the below restaurant object, I would like to update the addons
property of the optionalAddons
object with the value of addableIngredients
. How can I do so for each restaurant and each item?
"name": "4Cheeze",
"items": [
{
"name": "Chicken Grill",
"addableIngredients": "cheese - 2, mayo - 0",
"optionalAddons": {
"addable": 10,
"addons": ''
}
},
{
"name": "Fried Momo",
"addableIngredients": "cheese - 2, mayo - 0",
"optionalAddons": {
"addable": 10,
"addons": ''
}
},
],
}
Here is the Mongo playground link to play with: https://mongoplayground.net/p/JVjV2AiocHD
One option is to use an update with a pipeline to push the current value of addableIngredients
into the existing array:
db.collection.updateMany({},
[
{$set: {items: {$map: {
input: "$items",
in: {$mergeObjects: [
"$$this",
{optionalAddons: {addons: {
$mergeObjects: [
"$$this.optionalAddons",
{addons: {$concatArrays: [
"$$this.optionalAddons.addons",
["$$this.addableIngredients"]
]}}
]
}}}
]}
}}}}
])
See how it works on the playground example