[Mongo]分組統計時間 aggregate,group,distinct,mongoaggregate

來源:互聯網
上載者:User

[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裡面貼進來的,沒有格式,有點兒亂...有不明白的可以再問我
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.