【问题标题】:express mongoDB aggregation sumexpress mongoDB聚合总和
【发布时间】:2022-01-08 13:06:20
【问题描述】:

我的 mongodb 集合中有很多记录,我需要重新计算一些信息。

记录格式:

{
    "_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 并为 id ObjectId("603e0355e805140334e79438") 获取 SUM,但搜索的 id 可以是字段 targetFrom 或 targetTo 或 agent

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

sum 5000 即将到来,而 sum 3000 出局

【问题讨论】:

    标签: mongodb express mongoose aggregation


    【解决方案1】:

    查询

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

    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"]}}}}])
    

    【讨论】:

    • 还有一个问题。我需要添加什么才能仅获取字段 operationPaid 为 true 的记录?谢谢
    • 我想你的意思是this
    • 完全正确。再次感谢你! χρόνια πολλά με υγεία και αγάπη :P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 2022-10-13
    • 2013-07-20
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多