Mongodb 将返回子分组聚合为数组

Mongodb 将返回子分组聚合为数组,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有以下MongoDB查询: db.foo.aggregate([ {$unwind: "$Calculation.CustSatisfaction"} // important step! ,{$group: {_id: {country: "$Country", company: "$Company_ID", staff: "$Staff_ID", year: "$Calculation.C

我有以下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,
          }
}
我不知道该怎么做。非常感谢您的帮助。

再添加一个,内容如下:

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"
      }
    }
  }}
]);
允许在聚合管道中有多个阶段。因此,您的第一个阶段执行您想要的常规“累积”,第二个阶段简单地“上卷”到公共密钥的数组