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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Ohh, no, the query gave you the sum of all balances specifically for John Bolt. Here, i've updated the query in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.