表示mongoDB聚合总和

express mongoDB aggregation sum

我的mongodbcollection有很多记录,需要重新统计一些信息

记录格式:

{
    "_id" : someId,
    "targetFrom" : ObjectId("603e0355e805140334e79438"),<-- this is ID for search
    "targetTo" : null,
    "operationPaid" : true,
    "type" : "coming", <--- type
    "moneyAccount" : someId,
    "agent" : null,
    "sum" : 5000, <--- sum
}
{
    "_id" : someId,
    "targetFrom" : null,
    "targetTo" : null,
    "operationPaid" : true,
    "type" : "out", <--- type
    "moneyAccount" : someId,
    "agent" : ObjectId("603e0355e805140334e79438"),<-- this is ID for search
    "sum" : 3000, <--- sum
}

所以,我需要按记录分组 TYPE 并获得 SUM for id ObjectId("603e0355e805140334e79438"),但 id 用于搜索可以是字段 targetFromtargetToagent

对于这个例子,我需要得到结果 2000

sum 5000 coming sum 3000 out

查询

  • 匹配 3 个可能字段之一的 ID
  • 按空分组(所有集合 1 组),如果 type="out" 我减去总和字段,否则我添加到总和字段

Test code here

aggregate(
[{"$match":
  {"$expr":
   {"$or":
    [{"$eq":["$targetFrom", ObjectId("603e0355e805140334e79438")]},
     {"$eq":["$targetTo", ObjectId("603e0355e805140334e79438")]},
     {"$eq":["$agent", ObjectId("603e0355e805140334e79438")]}]}}},
 {"$group":
  {"_id":null,
   "sum":
   {"$sum":
    {"$cond":
     [{"$eq":["$type", "out"]}, {"$subtract":[0, "$sum"]}, "$sum"]}}}}])