1. 数据按照时间聚合操作

1.1 正常的数据结构
{
"_id" : ObjectId("5cac8d7b1202708adf5d4b64"),
"time" : ISODate("2019-04-09T20:18:03.308Z"),
"ip" : "10.10.23.2",
"metrics" : "bm",
"count" : NumberLong(3)
}
{
"_id" : ObjectId("5cac8d7c1202708adf5d4c75"),
"time" : ISODate("2019-04-09T20:18:04.062Z"),
"ip" : "10.13.23.2",
"metrics" : "bm",
"count" : NumberLong(0)
}
{
"_id" : ObjectId("5cac92a01202708adf613c88"),
"time" : ISODate("2019-04-09T20:40:00.024Z"),
"ip" : "10.13.23.2",
"metrics" : "bcc.proc.profile-bm",
"count" : NumberLong(0)
}
{
"_id" : ObjectId("5cac92a11202708adf613cb5"),
"time" : ISODate("2019-04-09T20:40:01.007Z"),
"ip" : "10.3.21.204",
"metrics" : "bcc.proc.profile-bm",
"count" : NumberLong(0)
}
1.2 mongo命令行查询

按照记录的时间指标,按照1分钟的纬度,进行统计聚合。

In the db.collection.aggregate method and db.aggregate method, pipeline stages appear in an array.

Documents pass through the stages in sequence.

aggregate函数中可以跟表达式,用到的表达式的如下所示:

$group Groups input documents by a specified identifier expression and applies the accumulator expression(s), if specified, to each group. Consumes all input documents and outputs one document per each distinct group. The output documents only contain the identifier field and, if specified, accumulated fields.

$match Filters the document stream to allow only matching documents to pass unmodified into the next pipeline stage. $match uses standard MongoDB queries. For each input document, outputs either one document (a match) or zero documents (no match).

$project Reshapes each document in the stream, such as by adding new fields or removing existing fields. For each input document, outputs one document.

$sort Reorders the document stream by a specified sort key. Only the order changes; the documents remain unmodified. For each input document, outputs one document.

db.count.aggregate(
{"$match":{ "time": {'$gte': ISODate("2019-04-09T14:00:00Z") ,'$lt':ISODate("2019-04-09T24:35:00Z")} }},
{"$group": { "_id": { "$subtract": [ { "$subtract": [ "$time", new Date("1970-01-01") ] }, { "$mod":[{"$subtract": ["$time", new Date("1970-01-01")]}, 1000 * 60 * 1 ]}]}, "total": {'$sum': '$count'}, } } ,
{"$project": { "_id": 0, 'datetime': {'$add': [new Date(0), '$_id']}, "total":1}},
{"$sort": { 'datetime': 1 }} )
1.3 golang mgo包查询:

golang 中mgo package中实现了mongo的聚合函数

func (c *Collection) Pipe(pipeline interface{}) *Pipe
For example:
pipe := collection.Pipe([]bson.M{{"$match": bson.M{"name": "Otavio"}}})
iter := pipe.Iter()

Pipe prepares a pipeline to aggregate. The pipeline document must be a slice built in terms of the aggregation framework language.

构造bson.M结构体,bson.M是map类型的定义。
这里主要解决三个问题:
1. 结构式的表达,整个结构式细分为子结构式
2. mongo $subtrace函数中需要的表达式为int类型的,主要将相应的数据类型转换为数值类型的
3. $mod表达式内部为表达式和数值的混合类型,用[]interface{}来表示, interface{}相当于C中的void*类型
m := []bson.M{}
type list []interface{}
date := time.Unix(0, 0)
sub := list{"$time", date}
sub_base := bson.M{"$subtract": sub} mode_list := list{sub_base, duration}
mode := bson.M{"$mod": mode_list} sub_array := []bson.M{}
sub_array = append(sub_array, sub_base)
sub_array = append(sub_array, mode) m = append(m, bson.M{"$match": bson.M{"time": bson.M{"$gte": bt, "$lte": et}, "ip": ip}})
m = append(m, bson.M{"$group": bson.M{"_id": bson.M{"$subtract": sub_array}, "count": bson.M{"$sum": "$count"}}}) add_list := list{date, "$_id"}
m = append(m, bson.M{"$project": bson.M{"_id": 0, "time": bson.M{"$add": add_list}, "count": 1}})
m = append(m, bson.M{"$sort": bson.M{"time": 1}})
count := make([]CountResult, 0)
err = count_db.Find(m, &count)

参考文档

  1. mongodb官方文档
  2. golang package

golang (4) golang 操作mongdb的更多相关文章

  1. golang 的 mysql 操作

    goLang的mysql操作,大致可分为三个步骤: 1.下载mysql驱动:go get github.com/go-sql-driver/mysql 2.建立连接:sql.Open("my ...

  2. Golang 调用 aws-sdk 操作 S3对象存储

    Golang 调用 aws-sdk 操作 S3对象存储 前言 因为业务问题,要写一个S3对象存储管理代码,由于一直写Go,所以这次采用了Go,Go嘛,快,自带多线程,这种好处就不用多说了吧. 基础的功 ...

  3. 【GoLang】golang HTTP GET/POST JSON的服务端、客户端示例,包含序列化、反序列化

    服务端代码示例: package main import ( "encoding/json" "fmt" "io/ioutil" " ...

  4. 【GoLang】GoLang map 非线程安全 & 并发度写优化

    Catena (时序存储引擎)中有一个函数的实现备受争议,它从 map 中根据指定的 name 获取一个 metricSource.每一次插入操作都会至少调用一次这个函数,现实场景中该函数调用更是频繁 ...

  5. 【golang】golang文本处理

    golang文本字符串操作:包含 合并 连接 分割 取索引 前缀后缀检测 消除字符串 消除空格 golang字符串操作需要用到 strings这个包 str := "hello world& ...

  6. node操作mongdb的常用函数示例

    node操作mongdb的常用函数示例 链接数据库 var mongoose = require('mongoose'); //引用数据库模块 mongoose.connect('mongodb:// ...

  7. golang: 利用unsafe操作未导出变量

    unsafe.Pointer其实就是类似C的void *,在golang中是用于各种指针相互转换的桥梁.uintptr是golang的内置类型,是能存储指针的整型,uintptr的底层类型是int,它 ...

  8. Golang原生sql操作Mysql数据库增删改查

    Golang要操作mysql数据库,首先需要在当期系统配置GOPATH,因为需要使用go get命令把驱动包下载到GOPATH下使用. 首先配置好你的GOPATH,执行以下命令,下载安装mysql驱动 ...

  9. golang的json操作

    package main import ( "encoding/json" "fmt" "os" ) type ConfigStruct s ...

随机推荐

  1. Java程序设计17——多线程-Part-B

    5 改变线程优先级 每个线程执行都具有一定的优先级,优先级高的线程获得较多的执行机会,而优先级低的线程则获得较少的执行机会. 每个线程默认的优先级都与创建它的父线程具有相同的优先级,在默认情况下,ma ...

  2. SpringCloud之自动化配置-config

    编程开发的时候有没有觉得很多配置文件需要维护,比如,修改了数据库连接,所有用到该数据库的服务配置都得替换,是不是超级的麻烦呢 下面,给大家介绍一下Spring提供的配置自动化组件-spring clo ...

  3. 超级详细的解决方法 (CentOS7) :永久修改 mysql read-only 问题 could not retrieve transation read-only status server

    一.查看mysql的事物隔离级别 SHOW VARIABLES LIKE '%iso%'; 二.临时修改事物隔离级别 SET GLOBAL tx_isolation='READ-COMMITTED'; ...

  4. Interceptor for {http://cxf.liuyang.com/}IHiServiceService has thrown exception, unwinding now org.apache.cxf.binding.soap.SoapFault: Error reading XMLStreamReader.

    Jquery同域访问:客户端连接服务器访问跨域访问:通过本地html文档,浏览器点击开访问(jquery不支持此访问) 用域名的方式访问http://localhost:8080/CXF_09_jqu ...

  5. Mac Sublime Text 浏览器 设置快捷键 让html文件在浏览器打开

    首先,进入命令行界面(这里mac和windows一样) 应用命令下载插件 输入命令二 然后就会发现在工具栏多出一个下拉选项 mac的跟它有些区别就是快捷键 mac快捷键是^+√+ V ++字母V,就会 ...

  6. thinkphp 调用wsdl接口实例化SoapClient抛出异常

    异常:Message:SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://*****?wsdl' : failed to load externa ...

  7. Ubuntu的常识使用了解3

    打包与压缩

  8. 【javascript】点击复制内容的实现

    各种站点有很多类似的代码,不过都是拿来即用,连个解释也没有.大概看了一下,现在主要使用的有两种办法: 1.documen.execCommand("Copy")或者window.c ...

  9. NG2-我们创建一个可复用的服务来调用英雄的数据

    <英雄指南>继续前行.接下来,我们准备添加更多的组件. 将来会有更多的组件访问英雄数据,我们不想一遍一遍地复制粘贴同样的代码. 解决方案是,创建一个单一的.可复用的数据服务,然后学着把它注 ...

  10. win32拖拽编程

    本文由作者邹启文授权网易云社区发布. 在邮箱大师PC版中,我们需要实现一个功能:账号和邮件夹拖拽排序. 准备 封装win32 API.我们使用到的API有, ImageList_Create.Imag ...