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?
2
Answers
You should need the update query with aggregation pipeline to reference the field.
$map
– Iterate the elements in theitems
array1.1.
$mergeObjects
– Merge the current iterated object with the document withprice
field.1.1.1.
$mergeObjects
– Merge theproduct.price
object with the document withdeposit
field referencing theproduct.price.pledge
value.Demo @ Mongo Playground
You can make use of updateMany() for this.
updateMany
targets all documents in the collection ({} as the firstargument).
$set
operator is used to assign the deposit field a value equalto the pledge field within each price object of each item in the
items array.
arrayFilters
specifies the conditions for the elements that theupdate should apply to. Here, it ensures the operation only applies
to elements where the pledge exists.
multi: true
option, although redundant in updateMany, emphasizesthe intention to update multiple documents. It’s more relevant in
update operations.
NOTE: Replace collectionName with the right name of your collection.
Edit: Making use of map and merge: