mongodb中两个分组值的总和?

时间:2016-06-04 17:47:46

标签: mongodb

Trans_Id      Account_Id     Amount   Tran_Type
   1             HA1001       1000       C
   2             HA1001         50       D
   3             HA1001        100       C
   4             HA1001        400       D

现在我如何计算帐户中的余额金额,例如sum of (C) - sum of (D) = 650

1 个答案:

答案 0 :(得分:1)

对于此聚合操作类型,tenary $cond 运算符将派上用场。您可以使用它来计算给定Tran_Type值的总和,因此您可以在 $group 管道阶段注入此逻辑,您将对所有文档进行分组(即分组空键)。您还需要管道 $project 运算符来计算与 $subtract 算术运算符的差异。

以下示例将演示此概念。运行管道操作以获得所需的结果:

填充测试文档:

db.test.insert([
    {
        "Trans_Id": 1,
        "Account_Id": "HA1001",
        "Amount": 1000,
        "Tran_Type": "C"
    },
    {
        "Trans_Id": 2,
        "Account_Id": "HA1001",
        "Amount": 50,
        "Tran_Type": "D"
    },
    {
        "Trans_Id": 3,
        "Account_Id": "HA1001",
        "Amount": 100,
        "Tran_Type": "C"
    },
    {
        "Trans_Id": 4,
        "Account_Id": "HA1001",
        "Amount": 400,
        "Tran_Type": "D"
    }
])

汇总渠道:

db.test.aggregate([
    {
        "$group": {
            "_id": null,
            "total_C": {
                "$sum": {
                    "$cond": [ 
                        { "$eq": [ "$Tran_Type", "C" ] }, 
                        "$Amount", 0 
                    ]
                }
            },
            "total_D": {
                "$sum": {
                    "$cond": [ 
                        { "$eq": [ "$Tran_Type", "D" ] }, 
                        "$Amount", 0 
                    ]
                }
            }
        }
    },
    {
        "$project": {
            "balance": {
                "$subtract": ["$total_C", "$total_D"]
            }, "_id": 0
        }
    }
])

示例输出:

{
    "result" : [ 
        { "balance" : 650 }
    ],
    "ok" : 1
}