[Mongo] 按时间分组统计(时间格式化)
分组的key可以使用原有的字段,也可以使用一个function来格式化日期。/* 0 */
{
"_id" : ObjectId("541fcc51c6c36038bc6b81cd"),
"url" : "http://wifi21.com/",
"addtime" : ISODate("2014-08-19T00:15:02Z")
}
/* 1 */
{
"_id" : ObjectId("541fcc51c6c36038bc6b81ce"),
"url" : "http://meiwen.me/src/index.html",
"addtime" : ISODate("2014-08-19T00:15:07Z")
}
...
统计代码:
db.msds_accessrecord.group({
keyf : function(doc){
var date = new Date(doc.addtime);
var dateKey = ""+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
return {'day':dateKey}; //33
},
initial : {"count":0},
reduce : function Reduce(doc, out) {
if(doc.url){
out.count +=1;
}
}
});
统计结果:
[
{
"day" : "2014-8-19",
"count" : 41
},
{
"day" : "2014-8-22",
"count" : 28
},
...
]
页:
[1]