Home >Database >Mysql Tutorial >[Mongo]按时间分组统计(时间格式化)

[Mongo]按时间分组统计(时间格式化)

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-07 16:03:181428browse

分组的key可以使用原有的字段,也可以使用一个function来格式化日期。 /* 0 */{ _id : ObjectId(541fcc51c6c36038bc6b81cd), url : http://wifi21.com/, addtime : ISODate(2014-08-19T00:15:02Z)}/* 1 */{ _id : ObjectId(541fcc51c6c36038bc6b81ce), url :

分组的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
        },
        ...
]

参考: http://stackoverflow.com/questions/5168904/group-by-dates-in-mongodb

本文出自 “orangleliu笔记本” 博客,请务必保留此出处 http://blog.csdn.net/orangleliu/article/details/39480359
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn