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音视频开发05-保存视频文件(yuv/h264/mp4)
一.前言 和音频存储类似,视频的存储也对应三种格式,视频最原始的数据是yuv(音频对应pcm),视频压缩后的数据是h264(音频对应aac),由于很多播放器或者早期的播放器不支持直接播放h264文件, ...
- Qt音视频开发32-Onvif网络设置
一.前言 用onvif协议来对设备的网络信息进行获取和设置,这个操作在众多的NVR产品中,用的很少,绝大部分用户都还是习惯直接通过摄像机的web页面进去配置,其实修改网络配置的功能在大部分的NVR中都 ...
- Vue.js 监听属性的使用
示例源码: <div id = "computed_props"> 千米 : <input type = "text" v-model = & ...
- 让我看看有多少人不知道Vue3中也能实现高阶组件HOC
前言 高阶组件HOC在React社区是非常常见的概念,但是在Vue社区中却是很少人使用.主要原因有两个:1.Vue中一般都是使用SFC,实现HOC比较困难.2.HOC能够实现的东西,在Vue2时代mi ...
- 聊一聊 C#异步中的Overlapped是如何寻址的
一:背景 1. 讲故事 前段时间训练营里的一位朋友提了一个问题,我用ReadAsync做文件异步读取时,我知道在Win32层面会传 lpOverlapped 到内核层,那在内核层回头时,它是如何通过这 ...
- 化繁为简、性能提升 -- 在WPF程序中,使用Freetype库心得
本人使用WPF开发了一款OFD阅读器,显示字体是阅读器中最重要的功能.处理字体显示有多种方案,几易其稿,最终选用Freetype方案.本文对WPF中如何使用Freetype做简单描述. OFD中有两种 ...
- C#轻松实现条形码二维码生成及识别
一.前言 大家好!我是付工. 今天给大家分享一下,如何基于C#来生成并识别条形码或者二维码. 二.http://ZXing.Net 实现二维码生成的库有很多,我们这里采用的是http://ZXing. ...
- Spring IOC实现原理,源码深度剖析!
Spring容器高层视图 Spring 启动时读取应用程序提供的Bean配置信息,并在Spring容器中生成一份相应的Bean配置注册表,然后根据这张注册表实例化Bean,装配好Bean之间的依赖关系 ...
- 领域驱动设计实战-DDD
--------------------- 领域驱动(DDD,Domain Driven Design)为软件设计提供了一套完整的理论指导和落地实践,通过战略设计和战术设计,将技术实现与业务逻辑分离, ...
- 部署Palworld幻兽帕鲁服务器最佳实践(Ubuntu)
本文为您介绍Ubuntu系统部署Palworld幻兽帕鲁服务器的最/佳实践. 1.登录云主机控制台,选择创建云主机的资源池,点击"创建云主机"按钮. 2.基础配置. CPU架构选择 ...