I have a data structure like this:
{
"_id": "order1",
"transactions": [
{
"amount": 100,
"type": "payment"
},
{
"amount": -10,
"type": "refund"
}
]
}
I want to get sum of amount which is 100+(-10) = 90. I am new to mongodb. Can someone help me write query.
you can use aggregate with $unwind
.aggregate([
{$unwind:"$transactions"},
{$group: {_id:"$_id", total: {$sum: "$transactions.amount"}}}
])