使用MongoDB的Go驱动库 mgo,对MongoDB的操作做一下简单封装

初始化
  • 操作没有用户权限的MongoDB
var globalS *mgo.Session

func init() {
s, err := mgo.Dial(dialInfo)
if err != nil {
log.Fatalf("Create Session: %s\n", err)
}
globalS = s
}
  • 如果MongoDB设置了用户权限需要使用下面的方法操作
func init() {
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
}
连接具体的数据和文档

每一次操作都copy一份 Session,避免每次创建Session,导致连接数量超过设置的最大值

获取文档对象 c := Session.DB(db).C(collection)

func connect(db, collection string) (*mgo.Session, *mgo.Collection) {
ms := globalS.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)
} // test
data := &Data{
Id: bson.NewObjectId().Hex(),
Title: "标题",
Des: "博客描述信息",
Content: "博客的内容信息",
Img: "https://upload-images.jianshu.io/upload_images/8679037-67456031925afca6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700",
Date: time.Now(),
} err := db.Insert("Test", "TestModel", data)
查询数据

db:操作的数据库

collection:操作的文档(表)

query:查询条件

selector:需要过滤的数据(projection)

result:查询到的结果

func FindOne(db, collection string, query, selector, result interface{}) error {
ms, c := connect(db, collection)
defer ms.Close() return c.Find(query).Select(selector).One(result)
} func FindAll(db, collection string, query, selector, result interface{}) error {
ms, c := connect(db, collection)
defer ms.Close() return c.Find(query).Select(selector).All(result)
} //test 查询title="标题",并且返回结果中去除`_id`字段
var result Data
err = db.FindOne(database, collection, bson.M{"title": "标题"}, bson.M{"_id":0}, &result)
更新数据

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": "更新标题"}})
删除数据

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"})
分页查询

db:操作的数据库

collection:操作的文档(表)

page:当前页面

limit:每页的数量值

query:查询条件

selector:需要过滤的数据(projection)

result:查询到的结果

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()

Golang 对MongoDB的操作简单封装的更多相关文章

  1. Golang使用MongoDB通用操作

    MongoDB是Nosql中常用的一种数据库,今天笔者就简单总结一下Golang如何使用这些通用的供能的,不喜勿喷... 研究的事例结构如下: type LikeBest struct { Autho ...

  2. MongoDB Helper的简单封装

    db.properties #mongodb数据库配置文件 #数据库server所在的ip地址 ip=127.0.0.1  #mongodb服务port号 port=27017 #要连接的库 dbNa ...

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

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

  4. 孤荷凌寒自学python第六十六天学习mongoDB的基本操作并进行简单封装5

    孤荷凌寒自学python第六十六天学习mongoDB的基本操作并进行简单封装5并学习权限设置 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十二天. 今天继续学习mongo ...

  5. 孤荷凌寒自学python第六十五天学习mongoDB的基本操作并进行简单封装4

    孤荷凌寒自学python第六十五天学习mongoDB的基本操作并进行简单封装4 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十一天. 今天继续学习mongoDB的简单操作 ...

  6. 孤荷凌寒自学python第六十四天学习mongoDB的基本操作并进行简单封装3

    孤荷凌寒自学python第六十四天学习mongoDB的基本操作并进行简单封装3 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十天. 今天继续学习mongoDB的简单操作, ...

  7. 孤荷凌寒自学python第六十三天学习mongoDB的基本操作并进行简单封装2

    孤荷凌寒自学python第六十三天学习mongoDB的基本操作并进行简单封装2 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第九天. 今天继续学习mongoDB的简单操作, ...

  8. 孤荷凌寒自学python第六十二天学习mongoDB的基本操作并进行简单封装1

    孤荷凌寒自学python第六十二天学习mongoDB的基本操作并进行简单封装1 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第八天. 今天开始学习mongoDB的简单操作, ...

  9. 简单封装mongodb

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

随机推荐

  1. buffer IO和direct IO

    最近在看很多框架,redis,kafka等底层都涉及到文件IO操作的效率问题,所以查了些资料,看到这篇文章讲的比较明白些,贴出来留存. 链接地址: https://www.ibm.com/develo ...

  2. JavaScript中的闭包永远都存储在内存中,除非关闭浏览器

    //閉包實現累加功能 function fn1() { var n = 1; add = function() { n += 1; } function fn2() { n += 1; console ...

  3. Moving or disabling the package cache for Visual Studio 2017

    Moving or disabling the package cache for Visual Studio 2017 | Setup & Install by Heath Stewart ...

  4. random模块,生成随机数

    1.random.choice(sep) 从一个序列中随机选取一个元素返回 >>> list1=["a",1,2,3,"b"] >> ...

  5. python 基础———— 字符串常用的调用 (图2)

    1.  replace 2.  join 3.split 4 rsplit 5. strip : 去除字符串左右两边特定(指定)的字符 7. rstrip  :  去除右边特定(指定)的字符 8. l ...

  6. jQuery获取元素的方法

    1·$(".box").offset().left 获取盒子左边到浏览器左侧的距离(上右下相同): 2·$("span").width() 获取盒子的宽度(高度 ...

  7. 关于String类学习的一些笔记(本文参考来自程序员考拉的文章)

    String 类继承自 Object 超类,实现的接口有:Serializable.CharSequence.Comparable<String> 接口,具体如下图: 一.常用的Strin ...

  8. SSM+MyBatis框架详解

  9. python_flask项目(BBS)_01

    项目文件用途说明: config.py   ,  此文件主要存储一些配置信息,如数据库连接串.debug模式串等. exts.py      ,  此文件装载第三方库实例对象,如sqlalchemy ...

  10. Tensoflow API笔记(N) 设备指定

        tf.device是tf.Graph.device()的一个包装,是一个用于指定新创建的操作(operation)的默认设备的环境管理器.参数为device_name_or_function, ...