我的数据格式为:
[{ _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 -无关紧要。
试试这个,
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]
}
}
]);