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 数据库驱动的更多相关文章

  1. C# Asp.net中简单操作MongoDB数据库(二)

    C# Asp.net中简单操作MongoDB数据库(一)    , mongodb数据库连接可以回顾上面的篇幅. 1.model类: public class BaseEntity { /// < ...

  2. C# Asp.net中简单操作MongoDB数据库(一)

    需要引用MongoDB.Driver.dll.MongoDB.Driver.core.dll.MongoDB.Bson.dll三个dll. 1.数据库连接: public class MongoDb ...

  3. 简单封装mongodb

    首先安装mongodb  npm i mongodb --save 简单封装,在modules目录下新建db.js var MongoClient=require('mongodb').MongoCl ...

  4. Python学习笔记_03:简单操作MongoDB数据库

    目录 1. 插入文档 2. 查询文档 3. 更新文档 4. 删除文档   1. 插入文档 # -*- coding: UTF-8 -*- import datetime from pymongo im ...

  5. 基于C#的MongoDB数据库开发应用(1)--MongoDB数据库的基础知识和使用

    在花了不少时间研究学习了MongoDB数据库的相关知识,以及利用C#对MongoDB数据库的封装.测试应用后,决定花一些时间来总结一下最近的研究心得,把这个数据库的应用单独作为一个系列来介绍,希望从各 ...

  6. 基于C#的MongoDB数据库开发应用(3)--MongoDB数据库的C#开发之异步接口

    在前面的系列博客中,我曾经介绍过,MongoDB数据库的C#驱动已经全面支持异步的处理接口,并且接口的定义几乎是重写了.本篇主要介绍MongoDB数据库的C#驱动的最新接口使用,介绍基于新接口如何实现 ...

  7. JAVA操作MongoDB数据库

    1. 首先,下载MongoDB对Java支持的驱动包 驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloads 2.Java操作Mo ...

  8. mongoDB数据库原生配置

    最近小冷在工作中使用到了mongoDB数据库,所以就简单的写了个demo,和大家简单分享下,如果大家也有想分享的东西或者需要分享的东西,生活或者其他都行,可以关注小冷公众号秦川以北或者加小冷微信qxy ...

  9. MongoDB Python官方驱动 PyMongo 的简单封装

    最近,需要使用 Python 对 MongodB 做一些简单的操作,不想使用各种繁重的框架.出于可重用性的考虑,想对 MongoDB Python 官方驱动 PyMongo 做下简单封装,百度一如既往 ...

  10. 封装对MongoDB数据库的增删改查访问方法(基于MongoDB官方发布的C#驱动)

    本文利用MongoDB官方发布的C#驱动,封装了对MongoDB数据库的增删改查访问方法.先用官方提供的mongo-csharp-driver ,当前版本为1.7.0.4714 编写数据库访问帮助类 ...

随机推荐

  1. 关于QtCreator中三种不同编译版本 debug、release、profile 的区别

    debug调试模式,编译后的可执行文件很大,带了很多调试符号信息等,方便开发阶段调试的时候进入具体的堆栈查看值.会打开所有的断言,运行阶段性能差速度慢,可能会有卡顿感觉. release发布模式,编译 ...

  2. C#中定义委托的思路

    如同在C#的类中定义成员变量或属性一样,类中定义成员变量(private)或属性(public),在类的构造方法中为变量或属性赋值或初始化. 在C#的类中定义委托变量同样遵循这个思路.首先声明一个委托 ...

  3. Python 添加类型标注 | 散发着自由松散气息的代码

    Python 添加类型标注 | 散发着自由松散气息的代码 Python 如此简洁,书写者在声明变量时甚至无需考虑类型. 但是简洁与复杂间,是存在一个平衡点的.当我们书写较为复杂的项目时,还是希望可以拥 ...

  4. Pytorch损失函数总结

    损失函数 nn.L1Loss 创建一个衡量输入中每个元素之间的平均绝对误差 (MAE) 的标准XX和目标是的是的. nn.MSELoss 创建一个标准,用于测量输入中每个元素之间的均方误差(平方 L2 ...

  5. golang自带的死锁检测并非银弹

    网上总是能看到有人说go自带了死锁检测,只要有死锁发生runtime就能检测到并及时报错退出,因此go不会被死锁问题困扰. 这说明了口口相传知识的有效性是日常值得怀疑的,同时也再一次证明了没有银弹这句 ...

  6. org.junit.Assert

    引入包,以下两种方式都是OK的,看个人喜好,我倾向于使用第二种,会更加清晰直观.下面的代码我都会用第二种 import static org.junit.Assert.*; import org.ju ...

  7. w3cschool-微信小程序开发文档-指南

    https://www.w3cschool.cn/weixinapp/9wou1q8j.html https://www.w3cschool.cn/miniappbook/ 微信小程序 小程序简介 小 ...

  8. javascript与css3动画学习笔记

    当Html5,css3已渐渐成为主流的时候,我还非常习惯的用js去做一些简单的动画.因为在桌面浏览器上, 并非所有的都支持css3.用户也倒是很奇怪,用户习惯并不是每个用户都可以被培养.总有不少人会觉 ...

  9. 解决使用PowerShell执行命令出现“因为在此系统上禁止运行脚本”的问题

    1.问题描述 出现的具体错误如下所示: 2.解决办法 以管理员身份运行PowerShell,执行命令get-executionpolicy可查看PowerShell执行的策略(Restricted代表 ...

  10. Linux查看和操作文件内容命令

    Linux查看和操作文件内容命令 文件查看命令 在Linux中,有多种命令可以帮助我们查看文件的内容.以下是其中一些常用的命令及其简要说明: cat命令 cat 命令用于显示文件的内容,特别适用于查看 ...