1

I have documents like this in my db:

{
"first_name": "John",
"last_name": "Bolt",
"account": [
  {
    "cardnumber": "4844615935257045",
    "cardtype": "jcb",
    "currency": "CZK",
    "balance": 4924.99
  },
  {
    "cardnumber": "3552058835710041",
    "cardtype": "jcb",
    "currency": "BRL",
    "balance": 9630.38
  },
  {
    "cardnumber": "5108757163721629",
    "cardtype": "visa-electron",
    "currency": "CNY",
    "balance": 6574.18
  }
}

And my question is - how can I sum balances for all accounts foreach person separately? Should I use for this Map-Reduce or Aggregation Framework?

saltwat5r
  • 1,107
  • 13
  • 21

1 Answers1

3

Use the aggregation framework.

This will give you an array of objects with two properties, id and balance where id contains the user's name.

db.document.aggregate([{
  $unwind: "$account"
}, {
  $group: {
    _id: {$concat: [ "$first_name", " ", "$last_name" ]},
    "balance": {
      $sum: "$account.balance"
    }
  }
}]);

Disclaimer: untested.

Ps: I sure hope that's dummy information. Here's another answer that might prove helpful.

Community
  • 1
  • 1
Amin Shah Gilani
  • 8,675
  • 5
  • 37
  • 79
  • Thanks for your response, but I want to get a list of all separated people with sum of all balances for each of them - not a sum of total balances of all people. – saltwat5r May 18 '15 at 10:09
  • 2
    Ohh, no, the query gave you the sum of all balances specifically for John Bolt. Here, i've updated the query in the answer. – Amin Shah Gilani May 18 '15 at 10:53