如何在 mongodb 中获取子集合的聚合
How to get aggregation of child collection in mongodb
我有这样的数据结构:
{
"_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 }
我有这样的数据结构:
{
"_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 }