我的数据格式为:
[{ _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 - 批评者,I - 无动于衷。