Khorshid
Khorshid

Reputation: 297

can I aggregate embedded documents in mongoDB by using dot notation?

I have a document in MongoDb like this:

{
        "_id" : ObjectId("56b88d5f2628a6bca1b17f99"),
        "first_name" : "JAMES",
        "last_name" : "SMITH",
        "accounts" : [
                {
                        "account_type" : "Savings",
                        "account_balance" : 8995952.153640702,
                        "currency" : "PESO"
                },
                {
                        "account_type" : "Checking",
                        "account_balance" : 3901436.5580737568,
                        "currency" : "USD"
                }
        ]
}

I want to group by "last_name" and "accounts.account_type" and summing every related balance.

I try dot notation like this but I have error and I couldn't find an explanation for this type of aggregation:

db.bank_data.aggregate([ 
{$group:{_id: "$last_name",accounts.account_type:"$accounts.acount_type",
 total:{$sum:"$accounts.account_balance"}}}])

Upvotes: 1

Views: 7724

Answers (1)

Koitoer
Koitoer

Reputation: 19533

Consider to unwind the account field in the aggregation pipeline first, and then grouping using the properties selected as it follows.

    db.bank_data.aggregate([
        {$unwind: '$accounts' },
        {$group: { _id: { last_name : "$last_name" , account_type: "$accounts.account_type" },
                  total:{$sum:"$accounts.account_balance"}
                 }
        }]);

Upvotes: 11

Related Questions