欢迎投稿

今日深度:

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

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


开发中有些按日期记录的记录需要各种维度的统计,按天,按月,按年,按小时,。。分组统计,还有些需要对字段去重统计,在之前的 [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")
}
...




按月统计pv值(相当于group)

db.msds_accessrecord.aggregate([
    {$group: {
        _id: {
            "$month": "$addtime"
        }, 
     pv: {$sum: 1}}
    },
    {$sort: {"_id": 1}}
]);

统计结果

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



按月统计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}}
]);
这里用到了管道,排序,聚合


统计结果

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


引用:

聚合使用方法: 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



mysql与mongo select count(distinct username) from log group by time

db.log.group({key:{time:1},cond:{},reduce:function(curr,result){if(result.arr.indexOf(curr.username)==-1){result.arr.push(curr.username);result.count++;}},initial:{arr:[],count:0}});

在本地验证过,initial方法初始化每个group结果的变量,reduce方法是每个group的各个值遍历执行的方法,这里arr是存储username来实现distinct,没有就往里插入并计数+1。从console里面贴进来的,没有格式,有点儿乱...有不明白的可以再问我
 


www.htsjk.Com true http://www.htsjk.com/shujukunews/3732.html NewsArticle [Mongo]分组统计时间 aggregate,group,distinct,mongoaggregate 开发中有些按日期记录的记录需要各种维度的统计,按天,按月,按年,按小时,。。分组统计,还有些需要对字段去重统计,在...
评论暂时关闭