Home > Database > Mysql Tutorial > body text

[Mongo]分组统计时间aggregate,group,distinct

WBOY
Release: 2016-06-07 16:04:41
Original
2355 people have browsed it

开发中有些按日期记录的记录需要各种维度的统计,按天,按月,按年,按小时,。。分组统计,还有些需要对字段去重统计,在之前的 [Mongo] 按时间分组统计(group时间格式化) 中用group实现了按天的统计,不过使用new Date()方法会有些坑,今天看了下aggreg

开发中有些按日期记录的记录需要各种维度的统计,按天,按月,按年,按小时,。。分组统计,还有些需要对字段去重统计,在之前的 [Mongo] 按时间分组统计(group时间格式化) 中用group实现了按天的统计,不过使用new Date()方法会有些坑,今天看了下aggregate中,使用聚合来写个时间统计。

tips: aggregate 挺复杂,弄明白了再做笔记,现在只是根据需求来查询。

数据结构还是:
/* 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")
}
...
Copy after login
按月统计pv值(相当于group)
db.msds_accessrecord.aggregate([
    {$group: {
        _id: {
            "$month": "$addtime"
        }, 
     pv: {$sum: 1}}
    },
    {$sort: {"_id": 1}}
]);
Copy after login

统计结果

/* 0 */
{
    "result" : [ 
        {
            "_id" : 8,
            "pv" : 583
        }, 
        {
            "_id" : 9,
            "pv" : 1399
        }
    ],
    "ok" : 1
} 
Copy after login

按月统计url值,重复url去掉,这里只是做个演示,可能统计没什么意义 (相当于group+distinct)

db.msds_accessrecord.aggregate([
    {$group: {
        _id: {
            "month": {"$month": "$addtime"},
            "url": "$url"
        }
    }},
    {$group: {_id:"$_id.month", uv: {$sum: 1}}},
    {$sort: {"_id":1}}
]);
Copy after login
这里用到了管道,排序,聚合

统计结果

/* 0 */
{
    "result" : [ 
        {
            "_id" : 8,
            "uv" : 41
        }, 
        {
            "_id" : 9,
            "uv" : 134
        }
    ],
    "ok" : 1
}
Copy after login

引用:

聚合使用方法: http://docs.mongodb.org/manual/reference/method/db.collection.aggregate/#db.collection.aggregate

日期聚合函数: http://docs.mongodb.org/manual/reference/operator/aggregation-date/

本文出自 “orangleliu笔记本” 博客,请务必保留此出处http://blog.csdn.net/orangleliu/article/details/39932081

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template