我有这样的数据结构:
{
"_id": "order1",
"transactions": [
{
"amount": 100,
"type": "payment"
},
{
"amount": -10,
"type": "refund"
}
]
}
我想获得100 +( - 10)= 90的金额之和。我是mongodb的新手。有人可以帮我写查询。
答案 0 :(得分:3)
您可以将汇总与$unwind
.aggregate([
{$unwind:"$transactions"},
{$group: {_id:"$_id", total: {$sum: "$transactions.amount"}}}
])
答案 1 :(得分:0)
> db.aaa.aggregate([{$unwind:"$transactions"},{$group:{_id:null, total:{$sum:"$transactions.amount"}}}])
{ "_id" : null, "total" : 90 }