Mongo视图中的总和和输出总数

时间:2018-04-25 19:29:06

标签: javascript mongodb aggregation-framework

在我的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

1 个答案:

答案 0 :(得分:3)

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

$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
}
然而,这可能只是一种矫枉过正的行为......