聚合返回子组作为数组

时间:2017-11-10 09:17:41

标签: mongodb aggregation-framework

我有以下MongoDB查询:

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"}
         }}
 ]);

但如果有多个月,它会给我多行。如何更改我的查询,使每个员工只有如下所示的行:

{
"_id" : {
    "country" : "MY",
    "company" : "MY01",
    "staff" : "NBJ64"
},
"Cust": [ { 
             "year": 2017,
             "month": 9
             "tHH" : 8,
             "tHN" : 0
          },
          { 
             "year": 2017,
             "month": 8
             "tHH" : 7,
             "tHN" : 0,
          }
},
{
"_id" : {
    "country" : "MY",
    "company" : "MY01",
    "staff" : "NBJ50"
},
"Cust": [ { 
             "year": 2017,
             "month": 9
             "tHH" : 1,
             "tHN" : 0
          },
          { 
             "year": 2017,
             "month": 8
             "tHH" : 4,
             "tHN" : 0,
          }
}

我不知道怎么能这样做。感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

再添加一个$group$push内容:

db.foo.aggregate([
  { "$unwind": "$Calculation.CustSatisfaction" },
  { "$group": {
    "_id": {
      "country": "$Country",
      "company": "$Company_ID",
      "staff": "$Staff_ID",
      "year": "$Calculation.CustSatisfaction.Trans_Year",
      "month": "$Calculation.CustSatisfaction.Trans_Month"
    },
    "tHH": { "$sum": "$Calculation.CustSatisfaction.HH" },
    "tHN": { "$sum": "$Calculation.CustSatisfaction.HN" }
  }},
  { "$group": {
    "_id": {
      "country": "$_id.counrty",
      "company": "$_id.company",
      "staff": "_id.staff"
    },
    "Cust": {
      "$push": {
        "year": "$_id.year",
        "month": "$_id.month",
        "tHH": "$tHH",
        "tHN": "$tHN"
      }
    }
  }}
]);

您可以在聚合管道中拥有多个$group阶段。所以你的第一阶段就是一般的积累"你想要的,第二个简单的"卷起"到公共密钥的数组。