0

我有一个数据结构是这样的:如何让孩子收集聚集在MongoDB中

{ 
    "_id": "order1", 
    "transactions": [ 
    { 
     "amount": 100, 
     "type": "payment" 
    }, 
    { 
     "amount": -10, 
     "type": "refund" 
    } 
    ] 
} 

我想量的总和是100 +( - 10)= 90。我是新来的MongoDB 。有人可以帮我写查询吗?

回答

2

您可以使用集合与$unwind

.aggregate([ 
{$unwind:"$transactions"}, 
{$group: {_id:"$_id", total: {$sum: "$transactions.amount"}}} 
]) 
0
> db.aaa.aggregate([{$unwind:"$transactions"},{$group:{_id:null, total:{$sum:"$transactions.amount"}}}]) 
{ "_id" : null, "total" : 90 }