Need mongodb query : if I get a order
, vendorID
in input params that already exists with specific orderNumber
I need to update it in orders
array by replacing the whole existing order element with that orderNumber
with newly provided order in input params, else insert it
Suppose input param has three attributes :
orderNumber : "order2"
order: {"orderNumber":"order2", "data":"NEW_DATA_FROM_INPUT" }
vendorId : "vendor1"
Here is the sample data in DB:
{
"_id":1,
"vendorId":"Vendor1",
"orders":[
{
"orderNumber":"order1",
"data":"data1"
},
{
"orderNumber":"order2",
"data":"data2"
}
]
}
THE QUERY SHOULD UPDATE THE RECORD AS BELOW:
{
"_id":1,
"vendorId":"Vendor1",
"orders":[
{
"orderNumber":"order1",
"data":"data1"
},
{
"orderNumber":"order2",
"data":"NEW_DATA_FROM_INPUT" // !!
}
]
}
Tried $set
, $addtoSet
but they cannot be used together on same path due to mongo limitations.
2
Answers
One way to do it is to use an aggregation pipeline in the update.
N.B.: Comments in
update
listing below. Depending on the app/driver you are using, you may need to changedb.collection.update
to something else (and you probably don’t want/need{"multi": true}
).Try it on mongoplayground.net where you will see various test cases.
In case of updation, we can use positional operation "$" with updateOne() or updateMany() which helps in updating the first occurrence to be updated with the provided values.
For eg. In the above case we need to update the 2nd index object value.