如何在mongodb中获取子集合的聚合
我的数据结构如下:如何在mongodb中获取子集合的聚合,mongodb,mongoose,mongodb-query,aggregation-framework,mongodb-aggregation,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,Mongodb Aggregation,我的数据结构如下: { "_id": "order1", "transactions": [ { "amount": 100, "type": "payment" }, { "amount": -10, "type": "refund" } ] } 我想得到的金额总和是100+(-10)=90。我是mongodb的新手。有人能帮我写查询吗。你可以使用聚合和$unwind .aggregate([ {$u
{
"_id": "order1",
"transactions": [
{
"amount": 100,
"type": "payment"
},
{
"amount": -10,
"type": "refund"
}
]
}
我想得到的金额总和是100+(-10)=90。我是mongodb的新手。有人能帮我写查询吗。你可以使用聚合和
$unwind
.aggregate([
{$unwind:"$transactions"},
{$group: {_id:"$_id", total: {$sum: "$transactions.amount"}}}
])
> db.aaa.aggregate([{$unwind:"$transactions"},{$group:{_id:null, total:{$sum:"$transactions.amount"}}}])
{ "_id" : null, "total" : 90 }