I have a collection of data like this:
{
"items": [
{
"product": {
"name": "prod1",
"price": {
"pledge": 1,
"cost": 19
}
}
},
{
"product": {
"name": "prod2",
"price": {
"pledge": 2,
"cost": 10
}
}
}
]
}
I want to update the whole collection have them like this:
{
"items": [
{
"product": {
"name": "prod1",
"price": {
"pledge": 1,
"deposit": 1,
"cost": 19
}
}
},
{
"product": {
"name": "prod2",
"price": {
"pledge": 2,
"deposit": 2,
"cost": 10
}
}
}
]
}
For each price in the items, I want to add a new field named deposit with the value of pledge in the same element.
How can I do it in an optimized way?
You should need the update query with aggregation pipeline to reference the field.
$map- Iterate the elements in theitemsarray1.1.
$mergeObjects- Merge the current iterated object with the document withpricefield.1.1.1.
$mergeObjects- Merge theproduct.priceobject with the document withdepositfield referencing theproduct.price.pledgevalue.Demo @ Mongo Playground