Mongodb根据日期字符串分组查询和Golang中的使用
简介在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"
}
}
}
])

二、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聚合分组查询的写法。
在使用Git的过程中,不想每次都输入用户名和密码去拉取代码,所以就需要保存这些信息,那么既然有保存了,就必须有清除功能。
我们在工作或是生活中,有时会需要制作一些请柬、奖状、或者桌牌等,这些东西都有一个共性,那就是除了每个人的名字不一样之外,其他大部分内容都是一样的,那么我们可以如何快速地批量制作呢?很简单,用Word的邮件合并功能就能做到!
ip命令是iproute软件包中的一个强大的网络配置工具,用于显示和管理Linux系统的路由、网络设备、策略路由和隧道。Centos7推荐使用ip命令代替传统的ipconfig和route[该命令我们没有进行说明,需要学习的请参考网上资料]命令。
Flutter的第一个程序“Hello World”
快速生成表格
Electron页面跳转、浏览器打开链接和打开新窗口
Docker编译镜像出现:fetch http://dl-cdn.alpinelinux.org/alpine/v3.12/main/x86_64/APKINDEX.tar.gz
ERROR: http://dl-cdn.alpinelinux.org/alpine/v3.12/main: temporary error (try again later)
WARNING: Ignoring APKINDEX.2c4ac24e.tar.gz: No such file or directory问题
在Mac电脑中,如何对Git的用户名和密码进行修改呢?起初不懂Mac,所以整了很久,本文将记录如何对这个进行操作,以便后期使用。