2

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.

chridam
  • 100,957
  • 23
  • 236
  • 235
Hemanth S R
  • 1,115
  • 2
  • 16
  • 27

2 Answers2

4

you can use aggregate with $unwind

.aggregate([
{$unwind:"$transactions"},
{$group: {_id:"$_id", total: {$sum: "$transactions.amount"}}}
])
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
0
> db.aaa.aggregate([{$unwind:"$transactions"},{$group:{_id:null, total:{$sum:"$transactions.amount"}}}])
{ "_id" : null, "total" : 90 }
Daphoque
  • 4,421
  • 1
  • 20
  • 31