-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.

1

1 Answer 1

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

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

Comments

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.