I have my orders collection as
[
{
_id:'134',
items:[
{
_id:'itemId1'
quantity: 2,
price: 100,,
couponsApplied:[]
},
{
_id:'itemId2'
quantity: 2,
price: 200,,
couponsApplied:[]
}
]
}
]
I want to apply 5% discount to each items above. i.e on
item _id:'itemId1'
, I want to push I want to push to couponsApplied as
{
couponAmount: 10, // quantity*price*percentage/100. which is 2*100*5/100
}
& Similarly on _id:’itemId2′, I want to push to couponsApplied as
{
couponAmount: 20,
}
So, after the update operation it should look like
[
{
_id:'134',
items:[
{
_id:'itemId1'
quantity: 2,
price: 100,,
couponsApplied:[
{
_id:'100',
couponAmount: 10
}
]
},
{
_id:'itemId2'
quantity: 2,
price: 200,,
couponsApplied:[
{
_id:'1002'
couponAmount: 20,
}
]
}
]
}
]
I have tried aggregate update with $mul and $sum but no luck
Please help!
2
Answers
A bit long update query.
$set
– Update theitems
array field.1.1.
$map
– Iterates withitems
array and returns an array.1.1.1.
$mergeObjects
– Merge current object withcouponsApplied
array field.1.1.1.1.
$concatArrays
– CombinecouponsApplied
array with the result of 1.1.1.1.1.1.1.1.1.1. An array with new document contains
couponAmount
field.Sample Mongo Playground
try this: