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聚合分组查询的写法。
快速生成表格
图像梯度计算的是图像变化的速度。对于图像的边缘部分,其灰度值变化较大,梯度值也较大;相反,对于图像中比较平滑的部分,其灰度值变化较小,相应的梯度值也较小。图像梯度计算需要求导数,但是图像梯度一般通过计算像素值的差来得到梯度的近似值(近似导数值)。本节主要介绍Sobel算子、Scharr算子、Laplacian算子和Canny算子的使用.
nodejs中使用npm和yarn,使用最新阿里云镜像 aliyun mirror,网上很多还是文章用的是下面这个地址~~yarn config set registry https://registry.npm.taobao.org~~
如何查看Mysql的二进制日志文件内容,其实Mysql本身就提供了一个命令就是mysqlbinlog,本文主要记录Mysql的mysqlbinlog命令的使用。
GitLab 是一个用于仓库管理系统的开源项目,使用Git作为代码管理工具,并在此基础上搭建起来的web服务。
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问题
在使用Git的过程中,不想每次都输入用户名和密码去拉取代码,所以就需要保存这些信息,那么既然有保存了,就必须有清除功能。
在Mac电脑中,如何对Git的用户名和密码进行修改呢?起初不懂Mac,所以整了很久,本文将记录如何对这个进行操作,以便后期使用。