Mongo Group By SUM

时间:2017-11-07 01:23:17

标签: c# mongodb

我有以下记录:

{
"_id" : ObjectId("5a0108d11b4af44a24d36e72"),
"Country" : "MY",
"Company_ID" : "MY01",
"Staff_ID" : "NBJ64",
"Calculation" : {
    "CustSatisfaction" : [ 
        {
            "Trans_Year" : 2017,
            "Trans_Month" : 7,
            "HH" : 10,
            "HN" : 0,
            "NH" : 4,
            "NN" : 0
        }, 
        {
            "Trans_Year" : 2017,
            "Trans_Month" : 7,
            "HH" : 1,
            "HN" : 0,
            "NH" : 5,
            "NN" : 0
        }
    ]
}
  }

我试图通过Trans_Year和Trans_Month得到HH,HN,NH,NN的SUM结果,如下所示:

{
"_id" : ObjectId("5a0108d11b4af44a24d36e72"),
"Country" : "MY",
"Company_ID" : "MY01",
"Staff_ID" : "NBJ64",
"Calculation" : {
    "CustSatisfaction" : [ 
        {
            "Trans_Year" : 2017,
            "Trans_Month" : 7,
            "HH" : 11,
            "HN" : 0,
            "NH" : 9,
            "NN" : 0
        }
    ]
}
  }

我总共有以下代码:

            var grouping = new BsonDocument {
        { "_id", new BsonDocument { { "build", "$WeCare.CustSatisfaction.Trans_Year" }, { "status", "$WeCare.CustSatisfaction.Trans_Month" } } },
        { "HH", new BsonDocument("$sum", 1)  }
    };
            var aggregate = mongoDB.Consultant.Aggregate().Group(grouping).ToList();

我得到的结果{{" _id" :{" build" :[2017年,2017年],"状态" :[7,7]}," HH" :1}}。这很奇怪。

1 个答案:

答案 0 :(得分:1)

好的,所以它本质上是一个5向组(国家,公司,员工,数组内的年份和月份)。这应该可以解决问题:

db.foo.aggregate([
{$unwind: "$Calculation.CustSatisfaction"} // important step!
,{$group: {_id: {country: "$Country",
             company: "$Company_ID",
             staff: "$Staff_ID",
             year: "$Calculation.CustSatisfaction.Trans_Year",
             mon: "$Calculation.CustSatisfaction.Trans_Month"},
       tHH: {$sum: "$Calculation.CustSatisfaction.HH"},
       tHN: {$sum: "$Calculation.CustSatisfaction.HN"},
       tNH: {$sum: "$Calculation.CustSatisfaction.NH"},
       tNN: {$sum: "$Calculation.CustSatisfaction.NN"}
}}
                ]);