Mongodb根据日期字符串分组查询和Golang中的使用

xiaohai 2020-08-20 14:54:21 4370人围观 标签: Go  MongoDB 
简介在Golang编程中,经常会用到MongoDB数据库进行查询,但是当日期是一个字符串的时候,如何根据日期进行分组查询呢?本文将记录如何分组查询统计。

在MongoDB中,如果记录的日期是字符串,现在要根据日期进行分时段统计数据,那么查询语句应该是怎么样的呢?

首先这里介绍下一个日志表中对应的字段:

  • app_id:应用ID
  • platform_id:平台ID
  • request_time:请求时间
  • time_length:时长

现在需要根据request_time来分组统计应用和平台在某一天所有时间段内的请求次数和平均响应时间。

一、MongoDB查询语句的写法
db.getCollection("request_logs202008").aggregate([ { //匹配条件 "$match": { "app_id": { "$ne": "", }, "platform_id": { "$ne": "", }, "request_time": { "$gte": "2020-08-19 00:00:00" } } }, { //匹配字段 "$project": { "app_id": "$app_id", "platform_id": "$platform_id", "time_length": "$time_length", "date": { "$substr": ["$request_time", 0, 10]//分割年月日 }, "hour": { "$substr": ["$request_time", 11, 2]//分割小时 }, } }, { //分组查询 "$group": { "_id": { "app_id": "$app_id", "platform_id": "$platform_id", "date": "$date", "hour": "$hour", }, "request_num": { "$sum": 1 }, "avg_response_time": { "$avg": "$time_length" } } } ])

image.png

二、Golang查询写法
//定义查询结构数据结构 var fieldGroup []struct { ID struct { AppId string `bson:"app_id"` PlatformId string `bson:"platform_id"` Date string `bson:"date"` Hour string `bson:"hour"` } `bson:"_id"` RequestNum uint32 `bson:"request_num"` AvgResponseTime float32 `bson:"avg_response_time"` } //组装查询,其实就是将MongoDB查询语句使用bson.M变换过来即可 pipeline := []bson.M{ //match bson.M{"$match": bson.M{ "app_id": bson.M{"$ne": ""}, "platform_id": bson.M{"$ne": ""}, "request_time": bson.M{"$gte": date + " 0:00:00"}, }}, //project bson.M{"$project": bson.M{ "app_id": "$app_id", "platform_id": "$platform_id", "time_length": "$time_length", "date": bson.M{"$substr": []interface{}{"$request_time", 0, 10}}, "hour": bson.M{"$substr": []interface{}{"$request_time", 11, 2}}, }}, //group bson.M{"$group": bson.M{ "_id": bson.M{ "app_id": "$app_id", "platform_id": "$platform_id", "date": "$date", "hour": "$hour", }, "request_num": bson.M{ "$sum": 1, }, "total_response_time": bson.M{ "$sum": "$time_length", }, "avg_response_time": bson.M{ "$avg": "$time_length", }, }}, } //这里需要使用Pipe进行查询 if err := libs.GetMongoDb().C("request_logs202008").Pipe(pipeline).All(&fieldGroup); err != nil { fmt.Println(err) }

以上就是记录整个MongoDB聚合分组查询的写法。