-1

I have a collection in below format

{customerID:1,acctDetails:[{accType:"Saving",balance:100},{accType:"checking",balance:500}]}
{customerID:2,acctDetails:[{accType:"Saving",balance:500}]}

I want to find total balance by acctType. I tried below query.

db.<collectionName>.aggregate([{$group:{_id:"$acctDetails.accType",totalBalance:{$sum:"$accDetails.balace"}}}])

But it is not giving right result.

Anil
  • 1,669
  • 5
  • 19
  • 44
  • 1
    Does this answer your question? [MongoDB group by array inner-elements](https://stackoverflow.com/questions/21509045/mongodb-group-by-array-inner-elements) or (https://stackoverflow.com/questions/33134523/mongodb-group-by-values-in-an-array-field) - you need to `$unwind` first ! – whoami - fakeFaceTrueSoul Jul 29 '20 at 14:32

1 Answers1

3

I think that this might solve your problem. You first need to use $unwind to transform each array element in a document, then use $group to sum the total balance by account type.

db.collection.aggregate([
  {"$unwind": "$acctDetails"},
  {
    "$group": {
      "_id": "$acctDetails.accType",
      "totalBalance": {"$sum": "$acctDetails.balance"}
    }
  }
])

Working Mongo playground