MongoDB计算$ unwind文档的总和

时间:2014-10-15 17:47:21

标签: mongodb mongodb-query

假设我有2个reports文档,其中嵌入了line_items文档:

包含line_items

的报告
{
    _id: "1",
    week_number: "1",
    line_items: [
       {
           cash: "5",
           miscellaneous: "10"
       },
       {
           cash: "20",
           miscellaneous: "0"
       }
    ]
},
{
    _id: "2",
    week_number: "2",
    line_items: [
       {
           cash: "100",
           miscellaneous: "0"
       },
       {
           cash: "10",
           miscellaneous: "0"
       }
    ]
}

我需要做的是在每个line_item上执行一组添加(在这种情况下为cash +杂项),并将报告查询中的总计设置为“粗略”字段。我想得到以下结果:

期望的结果

{ _id: "1", week_number: "1", gross: "35" },{ _id: "2", week_number: "2", gross: "110" }

我尝试过以下查询无济于事:

db.reports.aggregate([{$unwind: "$line_items"},{$group: {_id : "$_id", gross: {$sum : {$add: ["$cash", "$miscellaneous"]}}}}]);

1 个答案:

答案 0 :(得分:1)

您无法对字符串求和,因此您首先需要将文档中cashmiscellaneous字段的数据类型更改为数字类型。

但是一旦你这样做,你可以通过在line_items.命令中的那些字段上加上aggregate前缀来对它们求和:

db.reports.aggregate([
    {$unwind: "$line_items"},
    {$group: {
        _id : "$_id", 
        gross: {$sum : {$add: ["$line_items.cash", "$line_items.miscellaneous"]}}
    }}
]);

输出:

{
    "result" : [ 
        {
            "_id" : "2",
            "gross" : 110
        }, 
        {
            "_id" : "1",
            "gross" : 35
        }
    ],
    "ok" : 1
}