MongoDB聚合,用于将值重新整形或分组为字段名称和月份

时间:2016-08-23 18:37:32

标签: mongodb mongodb-query aggregation-framework mongodb-aggregation

我的数据格式为:

 [{ _id: 1, Prom: "I", date: ISOdate(2016-01-01 ... ) },
  { _id: 2, Prom: "P", date: ISOdate(2016-01-01 ... ) },
  { _id: 3, Prom: "D", date: ISOdate(2016-02-01 ... ) },
  { _id: 4, Prom: "I", date: ISOdate(2016-03-01 ... ) },
  { _id: 5, Prom: "I", date: ISOdate(2016-04-01 ... ) },
  { _id: 6, Prom: "D", date: ISOdate(2016-04-01 ... ) },
  { _id: 7, Prom: "P", date: ISOdate(2016-04-01 ... ) },
  ...
  { _id: 512, Prom: "I", date: ISOdate(2016-04-01 ... ) },
  { _id: 632, Prom: "P", date: ISOdate(2016-06-01 ... ) },
  { _id: 656, Prom: "I", date: ISOdate(2016-06-01 ... ) }]

然后我汇总数据以计算" P"," I"或" D"每月如此:

db.Collection.aggregate([
{
  $group: {
      _id: { Mnt:"$Mnt", Prom: "$Prom"} ,
      Count: {$sum: 1 },
  }
 }
]);

这给我的结果是:

 [{ "_id" : { "Mnt" : { "$date" : "2016-01-01T00:00:00.000+0000" }, "Prom" : "D" }, "Count" : 32 }
 { "_id" : { "Mnt" : { "$date" : "2016-01-01T00:00:00.000+0000" }, "Prom" : "P" }, "Count" : 138 }
 { "_id" : { "Mnt" : { "$date" : "2016-01-01T00:00:00.000+0000" }, "Prom" : "I" }, "Count" : 178 }
 { "_id" : { "Mnt" : { "$date" : "2016-02-01T00:00:00.000+0000" }, "Prom" : "D" }, "Count" : 46 }
 { "_id" : { "Mnt" : { "$date" : "2016-02-01T00:00:00.000+0000" }, "Prom" : "P" }, "Count" : 287 }
 { "_id" : { "Mnt" : { "$date" : "2016-02-01T00:00:00.000+0000" }, "Prom" : "I" }, "Count" : 197 }
  ....
 { "_id" : { "Mnt" : { "$date" : "2016-06-01T00:00:00.000+0000" }, "Prom" : "D" }, "Count" : 55 }
 { "_id" : { "Mnt" : { "$date" : "2016-06-01T00:00:00.000+0000" }, "Prom" : "P" }, "Count" : 42 }
 { "_id" : { "Mnt" : { "$date" : "2016-06-01T00:00:00.000+0000" }, "Prom" : "I" }, "Count" : 14 }]

如何将此数据分组或投影以格式表示我的数据?

[{ Mnt: ISOdate(2016-01-01 ...), "P": 138, "I": 178, "D": 32 },
 { Mnt: ISOdate(2016-02-01 ...), "P": 287, "I": 197, "D": 46 },
 ...
 { Mnt: ISOdate(2016-06-01 ...), "P": 42, "I": 14, "D": 55 }]

我真的没有找到一种方法来使用' Prom'作为管道中下一个聚合的关键。按月对该结果进行分组也存在问题。基本上我们想做的是按月从原始数据创建净推动者得分,P - 推动者,D - 诋毁者,我 - 无动于衷。

1 个答案:

答案 0 :(得分:0)

试试这个,

 db.Collection.aggregate([
    {
      $group: {
          _id: { Mnt:"$Mnt", Prom: "$Prom"} ,
          Count: {$sum: 1 },
      },
    $group: {
          _id:"$Mnt" ,res: { $push: "$Prom" }      
      },
    $project : { Mnt:$_id , res[0],res[1],res[2]

    }
     }
    ]);