统计任意时间段内和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日,每半小时的平均 repstime
和 total
之和.
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")
}