Kho*_*hid 1 mongodb aggregation-framework
我在MongoDb中有一个这样的文档:
{
"_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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我想按"last_name"和"accounts.account_type"进行分组,并汇总每个相关的余额.
我尝试像这样的点符号,但我有错误,我找不到这种聚合的解释:
db.bank_data.aggregate([
{$group:{_id: "$last_name",accounts.account_type:"$accounts.acount_type",
total:{$sum:"$accounts.account_balance"}}}])
Run Code Online (Sandbox Code Playgroud)
考虑首先在聚合管道中展开帐户字段,然后使用所选属性进行分组.
db.bank_data.aggregate([
{$unwind: '$accounts' },
{$group: { _id: { last_name : "$last_name" , account_type: "$accounts.account_type" },
total:{$sum:"$accounts.account_balance"}
}
}]);
Run Code Online (Sandbox Code Playgroud)