【问题标题】:Aggregate Return Sub-Grouping as an Array聚合返回子分组为数组
【发布时间】:2017-11-10 17:43:57
【问题描述】:

我有以下 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,
          }
}

我不知道该怎么做。感谢任何帮助。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案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 阶段。因此,您的第一阶段执行您想要的一般“累积”,第二阶段简单地“汇总”到公共键的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2015-11-16
      • 2011-04-15
      • 2019-04-28
      • 1970-01-01
      相关资源
      最近更新 更多