通过借记和贷记条目mongodb查找余额

时间:2017-11-12 14:46:36

标签: mongodb mongoose mongodb-query

我有一个像这样的Mongo系列:

{
    "user_id" : "1",
    "branch_id" : "1",
    "trans_type":"DEBIT",
    "total" : 500
},
{
    "user_id" : "1",
    "branch_id" : "1",
    "trans_type":"CREDIT",
    "total" : 200
},
{
    "user_id" : "1",
    "branch_id" : "3",
    "trans_type":"DEBIT",
    "total" : 1400
},
{
    "user_id" : "2",
    "branch_id" : "1",
    "trans_type":"DEBIT",
    "total" : 100
},
{
    "user_id" : "2",
    "branch_id" : "1",
    "trans_type":"CREDIT",
    "total" : 100
}

预期的输出是:

[
    {
        "user_id":"1",
        "branch_id":"1",
        "final_balance":"300"
    },
    {
        "user_id":"1",
        "branch_id":"3",
        "final_balance":"1400"
    },
    {
        "user_id":"2",
        "branch_id":"1",
        "final_balance":"0"
    }
]

请注意,在输出中,我在检查每个分支的每个用户的借方和贷方分录后,正在寻找最终余额。

谢谢。

1 个答案:

答案 0 :(得分:1)

这听起来像一个简单的$group$cond会为你完成这项任务:

db.collection.aggregate({
    $group: {
        "_id": { // group by both fields, "user_id" and "branch_id"
            "user_id": "$user_id",
            "branch_id": "$branch_id"
        },
        "final_balance": {
            $sum: { // calculate the sum of all "total" values
                $cond: {
                    if: { $eq: [ "$trans_type", "DEBIT" ] }, // in case of "DEBIT", we want the stored value for "total"
                    then: "$total", 
                    else: { $multiply: [ "$total", -1 ] } // otherwise we want the stored value for "total" times -1
                }
            }
        }
    }
}, {
    $project: { // this is not really needed unless you specifically need the output format you mentioned in the question
        "_id": 0,
        "user_id": "$_id.user_id",
        "branch_id": "$_id.branch_id",
        "final_balance": "$final_balance",
    }
})