[MongoDB] 按时间分组统计(任意时间段)

版权声明:本文为orangleliu (http://blog.csdn.net/orangleliu/)原创文章,自由传播,文章转载请声明, 多谢。 https://blog.csdn.net/lzz957748332/article/details/79864624

统计任意时间段内和sum,avg等信息

记录样本

{
    "_id" : ObjectId("5a2a290320fc1abc16104c0c"),
    "netservice" : "Brasil_OiVelox",
    "repstime" : 0.014,
    "stattime" : ISODate("2017-12-08T13:45:00.000Z"),
    "total" : 1,
    "dnstime" : 0.191,
    "city" : "圣保罗",
    "district" : "巴西",
    "success" : 1,
    "created" : ISODate("2017-12-08T13:54:11.361Z"),
    "bufrate" : 0.0,
    "first_frame" : 0.383,
    "downspeed" : 2274.243,
    "tcptime" : 0.015
}

比如现在要统计 2018-03-11 ~12日,每半小时的平均 repstimetotal 之和.

db.getCollection('test-fa-test-07132-PK').aggregate(
    {"$match":{
        "stattime": {'$gte': ISODate("2018-03-11T00:00:00Z")  ,'$lt':ISODate("2018-03-12T00:00:00Z")}
    }},
    {"$group": {
        "_id": { 
            "$subtract": [
                { "$subtract": [ "$stattime", new Date("1970-01-01") ] },
                { "$mod": [
                    { "$subtract": [ "$stattime", new Date("1970-01-01") ] },
                    1000 * 60 * 30 /*聚合时间段,30分钟*/
                ]}
            ]
        },
        "repstime": {'$avg': '$repstime'},
        "total": {'$sum': '$total'},
        //"timelist": { '$push': '$stattime'} /*查看聚合那些时间*/
  }},
    {"$project": {
            "_id": 0,
            "repstime": 1,
            "total":1,
            "timelist": 1,
            'datetime': {'$add': [new Date(0), '$_id']}                  
    }},
    {"$sort": {
        'datetime': 1
    }}
)

查询结果

/* 1 */
{
    "repstime" : 0.141346153846154,
    "total" : 26,
    "datetime" : ISODate("2018-03-11T00:00:00.000Z")
}

/* 2 */
{
    "repstime" : 0.0664772727272727,
    "total" : 44,
    "datetime" : ISODate("2018-03-11T00:30:00.000Z")
}
阅读更多
换一批

没有更多推荐了,返回首页