设为首页 加入收藏

TOP

[Mongo]分组统计时间aggregate,group,distinct
2014-11-24 07:45:08 来源: 作者: 【 】 浏览:1
Tags:Mongo 分组 统计 时间 aggregate group distinct
开发中有些按日期记录的记录需要各种维度的统计,按天,按月,按年,按小时,。。分组统计,还有些需要对字段去重统计,在之前的 [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插入Emoji表情报错 下一篇PostgreSQL之查找最慢的SQL

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·About - Redis (2025-12-26 08:20:56)
·Redis: A Comprehens (2025-12-26 08:20:53)
·Redis - The Real-ti (2025-12-26 08:20:50)
·Bash 脚本教程——Li (2025-12-26 07:53:35)
·实战篇!Linux shell (2025-12-26 07:53:32)