首页 > 解决方案 > 在 Mongo 视图中求和和输出总计

问题描述

在我的 mongDB 后端,我有一个视图,在多个聚合阶段之后,输出如下所示的信息:

{ 
    "_id" : 25k3ejfjyi32132f9z3,
    "customer_id" : 15cgrd582950jj493g5,
    "openBalance": 24,
    // other data...
},
{ 
    "_id" : 35g6ejfjfj32132f8s4, 
    "customer_id" : 23gtrd684563jj494f4
    "openBalance": 20,
    // other data...
}

作为最后一步,我需要做的是汇总所有记录的所有“openBalance”金额,并将该数字与其他数据一起输出到新字段中。所以,换句话说,根据上面的数据,我想44在一个名为totalOpenBalance.

有没有办法可以在 mongo 视图中处理这个聚合逻辑?我不知道该怎么做,因为我不想为返回的每条记录添加一个字段,而是根据记录的总数返回一个值?它看起来像这样:

{ 
    "_id" : 25k3ejfjyi32132f9z3,
    "customer_id" : 15cgrd582950jj493g5,
    "openBalance": 24,
    // other data...
},
{ 
    "_id" : 35g6ejfjfj32132f8s4, 
    "customer_id" : 23gtrd684563jj494f4
    "openBalance": 20,
    // other data...
},
"totalOpenBalance": 44

标签: javascriptmongodbaggregation-framework

解决方案


如果将以下代码添加到管道的末尾

$group: {
    _id: null, // do not really group but throw all documents into the same bucket
    documents: { $push: "$$ROOT" }, // push each encountered document into the group
    totalOpenBalance: { $sum: "$openBalance" } // sum up all "openBalance" values
}

你会得到一些你可以使用的东西:

{
    "_id" : null,
    "documents" : [ 
        {
            "_id" : 25k3ejfjyi32132f9z3,
            "customer_id" : 15cgrd582950jj493g5,
            "openBalance" : 24
        }, 
        {
            "_id" : 35g6ejfjfj32132f8s4,
            "customer_id" : 23gtrd684563jj494f4,
            "openBalance" : 20
        }
    ],
    "totalOpenBalance" : 44
}

如果您想完全发疯,我不建议您继续阅读。通过添加以下阶段

{
    $group: {
        _id: null, // do not really group but throw all documents into the same bucket
        documents: { $push: "$$ROOT" }, // push each encountered document into the group
        totalOpenBalance: { $sum: "$openBalance" } // sum up all "openBalance" values
    }
}, {
    $project: {
        "_id": 0, // remove the "_id" field
        "documents": { $concatArrays: [ "$documents", [ { "totalOpenBalance": "$totalOpenBalance" } ] ] } // append a magic subdocument to the the existing documents
    }
}, {
    $unwind: "$documents" // just so we can flatten the resulting array into separate documents
}, {
    $replaceRoot: {
        newRoot: "$documents" // and move the content of our documents field to the root
    }
}

你得到的正是你所要求的:

{
    "_id" : 25k3ejfjyi32132f9z3,
    "customer_id" : 15cgrd582950jj493g5,
    "openBalance" : 24
},
{
    "_id" : 35g6ejfjfj32132f8s4,
    "customer_id" : 23gtrd684563jj494f4,
    "openBalance" : 20
},
{
    "totalOpenBalance" : 44
}

然而,这可能只是矫枉过正......


推荐阅读