Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在mongodb中获取子集合的聚合_Mongodb_Mongoose_Mongodb Query_Aggregation Framework_Mongodb Aggregation - Fatal编程技术网

如何在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 }