go mgo包 简单封装 mongodb 数据库驱动
mgo是go编写的mongodb的数据库驱动,集成到项目中进行mongodb的操作很流畅,以下是对其的一些简单封装,具体使用可随意改动封装。
安装
go get gopkg.in/mgo.v2
使用
引入第三方包
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
初始化连接
var (
GVA_MONGO_DB *mgo.Session
)
global.GVA_MONGO_DB = initialize.Mongodb()
// 如果MongoDB设置了用户权限需要使用下面的方法操作
func Mongodb() *mgo.Session {
//dialInfo := &mgo.DialInfo{
// Addrs: []string{dbhost}, //数据库地址 dbhost: mongodb://user@123456:127.0.0.1:27017
// Timeout: timeout, // 连接超时时间 timeout: 60 * time.Second
// Source: authdb, // 设置权限的数据库 authdb: admin
// Username: authuser, // 设置的用户名 authuser: user
// Password: authpass, // 设置的密码 authpass: 123456
// PoolLimit: poollimit, // 连接池的数量 poollimit: 100
//}
//
//s, err := mgo.DialWithInfo(dialInfo)
//if err != nil {
// log.Fatalf("Create Session: %s\n", err)
//}
//globalS = s
s, err := mgo.Dial("127.0.0.1:27017")
if err != nil {
log.Fatalf("Create Session: %s\n", err)
}
return s
}
连接具体的数据和文档
每一次操作都copy一份 Session,避免每次创建Session,导致连接数量超过设置的最大值
获取文档对象 c := Session.DB(db).C(collection)
func connect(db, collection string) (*mgo.Session, *mgo.Collection) {
ms := global.GVA_MONGO_DB.Copy()
c := ms.DB(db).C(collection)
ms.SetMode(mgo.Monotonic, true)
return ms, c
}
插入数据
每次操作之后都要主动关闭 Session defer Session.Close()
db:操作的数据库
collection:操作的文档(表)
doc:要插入的数据
func Insert(db, collection string, doc interface{}) error {
ms, c := connect(db, collection)
defer ms.Close()
return c.Insert(doc)
}
// bson映射真实对应mongodb中的字段值
type Incomes struct {
Symbol string `bson:"symbol"` // 交易对
Income float64 `bson:"income"` // 资金流数量,正数代表流入,负数代表流出
CreatedAt int64 `bson:"created_at"` // 创建时间
}
inComes := Incomes{
Symbol: "BTCUSDT",
Income: "12312",
CreatedAt: 1618489385,
}
err := db.Insert("Fund", "Incomes", inComes)
查询数据
db:操作的数据库
collection:操作的文档(表)
query:查询条件
selector:需要过滤的数据(projection)
result:查询到的结果
func FindOne(db, collection, sort string, query, selector, result interface{}) error {
ms, c := connect(db, collection)
defer ms.Close()
return c.Find(query).Select(selector).Sort(sort).One(result)
}
func FindAll(db, collection, sort string, query, selector, result interface{}) error {
ms, c := connect(db, collection)
defer ms.Close()
return c.Find(query).Select(selector).Sort(sort).All(result)
}
可自定义修改封装
排序 Sort
//按age升序,如果要降序Sort("-age")
iter = c.Find(bson.M{"age": bson.M{"$gte": 33}}).Sort("age").Iter()
限定结果数量 Limit
//使用Limit限定只去5条记录
iter = c.Find(bson.M{"age": bson.M{"$gte": 20}}).Sort("age").Limit(5).Iter()
跳过指定数量的记录 Skip
//跳过两条记录,取接下来的5条记录
iter = c.Find(bson.M{"age": bson.M{"$gte": 20}}).Sort("age").Skip(2).Limit(5).Iter()
计算记录的条数 Count
recordsCount, err := c.Find(bson.M{"age": bson.M{"$gte": 20}}).Count()
示例
// 查询title="标题"【=($eq)】,并且返回结果中去除`_id`字段
var result Data
err = db.FindOne(database, collection, bson.M{"title": "标题"}, bson.M{"_id":0}, &result)
// 根据created_at排序 默认正序
fundNetValue := model.FundNetValue{}
mongodb.FindOne("Fund", "netValue", "-created_at", bson.M{}, bson.M{}, &fundNetValue)
// 根据created_at排序 加-连接号 为倒序
mongodb.FindAll("Fund", "netAssets", bson.M{"-created_at": bson.M{"$gt": time - 86400, "$lte": time}}, bson.M{}, fundNetAssets)
// !=($ne)
bson.M{"name": bson.M{"$ne": "Jimmy Kuu"}}
// >($gt)
bson.M{"age": bson.M{"$lt": 32}}
// <($lt)
bson.M{"age": bson.M{"$lt": 32}}
// >=($gte)
bson.M{"age": bson.M{"$gte": 33}}
// <=($lte)
bson.M{"age": bson.M{"$lte": 31}}
// in($in)
bson.M{"name": bson.M{"$in": []string{"Jimmy Kuu", "Tracy Yu"}}}
// not in($nin)
bson.M{"name": bson.M{"$nin": []string{"Jimmy Kuu", "Tracy Yu"}}}
// 是否包含存在($exists)
bson.M{"city": bson.M{"$exists": true}}
// 键值为null(键存在,键值为null)
bson.M{"city": bson.M{"$in": []interface{}{nil}, "$exists": true}}
// $size 键值长度为指定值的数组
bson.M{"interests": bson.M{"$size": 3}}
// $all 包含所有值的匹配
bson.M{"interests": bson.M{"$all": []string{"music", "reading"}}}
// 多条件查询
// and($and)
bson.M{"city": "Shanghai", "age": bson.M{"$gte": 33}}
// or($or)
bson.M{"$or": []bson.M{bson.M{"name": "Jimmy Kuu"}, bson.M{"age": 31}}}
更新数据
db:操作的数据库
collection:操作的文档(表)
selector:更新条件
update:更新的操作
func Update(db, collection string, selector, update interface{}) error {
ms, c := connect(db, collection)
defer ms.Close()
return c.Update(selector, update)
}
//更新,如果不存在就插入一个新的数据 `upsert:true`
func Upsert(db, collection string, selector, update interface{}) error {
ms, c := connect(db, collection)
defer ms.Close()
_, err := c.Upsert(selector, update)
return err
}
// `multi:true`
func UpdateAll(db, collection string, selector, update interface{}) error {
ms, c := connect(db, collection)
defer ms.Close()
_, err := c.UpdateAll(selector, update)
return err
}
示例
//test
err = db.Update(database, collection, bson.M{"_id": "5b3c30639d5e3e24b8786540"}, bson.M{"$set": bson.M{"title": "更新标题"}})
// 修改字段的值($set)
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")}, bson.M{"$set": bson.M{ "name": "Jimmy Gu", "age": 34, }}
// 字段增加值 inc($inc)
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")}, bson.M{"$inc": bson.M{ "age": -1, }}
// 从数组中增加一个元素 push($push)
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")}, bson.M{"$push": bson.M{ "interests": "Golang", }}
// 从数组中删除一个元素 pull($pull)
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")}, bson.M{"$pull": bson.M{ "interests": "Golang", }}
删除数据
db:操作的数据库
collection:操作的文档(表)
selector:删除条件
func Remove(db, collection string, selector interface{}) error {
ms, c := connect(db, collection)
defer ms.Close()
return c.Remove(selector)
}
func RemoveAll(db, collection string, selector interface{}) error {
ms, c := connect(db, collection)
defer ms.Close()
_, err := c.RemoveAll(selector)
return err
}
//test
err = db.Remove(database,collection,bson.M{"_id":"5b3c30639d5e3e24b8786540"})
分页查询
func FindPage(db, collection string, page, limit int, query, selector, result interface{}) error {
ms, c := connect(db, collection)
defer ms.Close()
return c.Find(query).Select(selector).Skip(page * limit).Limit(limit).All(result)
}
其他操作
func IsEmpty(db, collection string) bool {
ms, c := connect(db, collection)
defer ms.Close()
count, err := c.Count()
if err != nil {
log.Fatal(err)
}
return count == 0
}
func Count(db, collection string, query interface{}) (int, error) {
ms, c := connect(db, collection)
defer ms.Close()
return c.Find(query).Count()
}
go mgo包 简单封装 mongodb 数据库驱动的更多相关文章
- C# Asp.net中简单操作MongoDB数据库(二)
C# Asp.net中简单操作MongoDB数据库(一) , mongodb数据库连接可以回顾上面的篇幅. 1.model类: public class BaseEntity { /// < ...
- C# Asp.net中简单操作MongoDB数据库(一)
需要引用MongoDB.Driver.dll.MongoDB.Driver.core.dll.MongoDB.Bson.dll三个dll. 1.数据库连接: public class MongoDb ...
- 简单封装mongodb
首先安装mongodb npm i mongodb --save 简单封装,在modules目录下新建db.js var MongoClient=require('mongodb').MongoCl ...
- Python学习笔记_03:简单操作MongoDB数据库
目录 1. 插入文档 2. 查询文档 3. 更新文档 4. 删除文档 1. 插入文档 # -*- coding: UTF-8 -*- import datetime from pymongo im ...
- 基于C#的MongoDB数据库开发应用(1)--MongoDB数据库的基础知识和使用
在花了不少时间研究学习了MongoDB数据库的相关知识,以及利用C#对MongoDB数据库的封装.测试应用后,决定花一些时间来总结一下最近的研究心得,把这个数据库的应用单独作为一个系列来介绍,希望从各 ...
- 基于C#的MongoDB数据库开发应用(3)--MongoDB数据库的C#开发之异步接口
在前面的系列博客中,我曾经介绍过,MongoDB数据库的C#驱动已经全面支持异步的处理接口,并且接口的定义几乎是重写了.本篇主要介绍MongoDB数据库的C#驱动的最新接口使用,介绍基于新接口如何实现 ...
- JAVA操作MongoDB数据库
1. 首先,下载MongoDB对Java支持的驱动包 驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloads 2.Java操作Mo ...
- mongoDB数据库原生配置
最近小冷在工作中使用到了mongoDB数据库,所以就简单的写了个demo,和大家简单分享下,如果大家也有想分享的东西或者需要分享的东西,生活或者其他都行,可以关注小冷公众号秦川以北或者加小冷微信qxy ...
- MongoDB Python官方驱动 PyMongo 的简单封装
最近,需要使用 Python 对 MongodB 做一些简单的操作,不想使用各种繁重的框架.出于可重用性的考虑,想对 MongoDB Python 官方驱动 PyMongo 做下简单封装,百度一如既往 ...
- 封装对MongoDB数据库的增删改查访问方法(基于MongoDB官方发布的C#驱动)
本文利用MongoDB官方发布的C#驱动,封装了对MongoDB数据库的增删改查访问方法.先用官方提供的mongo-csharp-driver ,当前版本为1.7.0.4714 编写数据库访问帮助类 ...
随机推荐
- Qt编写音频播放示例(带音频曲线/振幅/传输/录制等)
一.功能特点 自动计算音频振幅,绘制音频振幅曲线和音频数据曲线. 支持音频录制,可选音频输入设备.采样频率.通道等参数,Qt5默认保存wav格式,Qt6默认保存mp3格式,Qt6可选wma.aac等格 ...
- Qt交叉编译整理的几点说明
关于交叉编译,对于初学者来说是个极难跨过去的砍(一旦跨过去了,以后遇到需要交叉编译的时候都是顺水推舟.信手拈来.),因为需要搭建交叉编译环境,好在现在厂家提供的板子基本上都是测试好的环境,尤其是提供的 ...
- Qt开发经验小技巧191-195
关于QList队列的处理中,我们最常用的就是调用append函数添加item,往前插入item很多人第一印象就是调用insert(0,xxx)来插入,其实QList完全提供了往前追加item的函数pr ...
- UML之关联
关联指两个类之间的各种联系.UML使用各种单实线表示关联,这个单实线可以是直线(垂直的.水平的或者倾斜的).折线甚至曲线. 事实上,关联也是展示类的属性的另一外的一种形式.例如在下图中,我们通过一条实 ...
- 前端学习openLayers配合vue3(图层中心点的偏移)
有了上一步的学习,我们知道了如何创建一个地图,现在我们来尝试更改一下图层的中心点 关键代码 let view = map.getView();//获取视图层 let center = view.get ...
- No match for argument: kde-l10n-Chinese 报错
背景:安装 kde-l10n-Chinese 软件包报错 原因:该安装包适用于 centos7 系统,若为 centos8 则无法安装 解决办法:更换适配 centos 8 中文安装包 yum ins ...
- Solution Set -「DS 专题」兔年的兔子写 DS 会有小常数吗?
目录 Day 1 「Ynoi 2009」「洛谷 P6109」rprmq1 ^ 「Ynoi Easy Round 2021」「洛谷 P8512」TEST_152 「Ynoi 2005」「洛谷 P7907 ...
- 安装K8s集群
因阿里云加速服务调整,镜像加速服务自2024年7月起不再支持,拉取镜像,下载网络插件等操作,需要国际联网访问DockerHub. 安装全过程均使用ROOT权限. 1.安装前准备工作 这里采用3台Cen ...
- 面试题:区分List中remove(int index)和remove(Object obj)
面试题:区分List中remove(int index)和remove(Object obj) package com.atguigu.exer;import org.junit.Test;impor ...
- DPDK简介和原理
本文分享自天翼云开发者社区<DPDK简介和原理>,作者:s****n DPDK是一种绕过内核直接在用户态收发包来解决内核性能的瓶颈技术. 什么是中断 了解DPDK之前,首先需要先了解什么是 ...