Golang 对MongoDB的操作简单封装
使用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的操作简单封装的更多相关文章
- Golang使用MongoDB通用操作
MongoDB是Nosql中常用的一种数据库,今天笔者就简单总结一下Golang如何使用这些通用的供能的,不喜勿喷... 研究的事例结构如下: type LikeBest struct { Autho ...
- MongoDB Helper的简单封装
db.properties #mongodb数据库配置文件 #数据库server所在的ip地址 ip=127.0.0.1 #mongodb服务port号 port=27017 #要连接的库 dbNa ...
- MongoDB Python官方驱动 PyMongo 的简单封装
最近,需要使用 Python 对 MongodB 做一些简单的操作,不想使用各种繁重的框架.出于可重用性的考虑,想对 MongoDB Python 官方驱动 PyMongo 做下简单封装,百度一如既往 ...
- 孤荷凌寒自学python第六十六天学习mongoDB的基本操作并进行简单封装5
孤荷凌寒自学python第六十六天学习mongoDB的基本操作并进行简单封装5并学习权限设置 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十二天. 今天继续学习mongo ...
- 孤荷凌寒自学python第六十五天学习mongoDB的基本操作并进行简单封装4
孤荷凌寒自学python第六十五天学习mongoDB的基本操作并进行简单封装4 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十一天. 今天继续学习mongoDB的简单操作 ...
- 孤荷凌寒自学python第六十四天学习mongoDB的基本操作并进行简单封装3
孤荷凌寒自学python第六十四天学习mongoDB的基本操作并进行简单封装3 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十天. 今天继续学习mongoDB的简单操作, ...
- 孤荷凌寒自学python第六十三天学习mongoDB的基本操作并进行简单封装2
孤荷凌寒自学python第六十三天学习mongoDB的基本操作并进行简单封装2 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第九天. 今天继续学习mongoDB的简单操作, ...
- 孤荷凌寒自学python第六十二天学习mongoDB的基本操作并进行简单封装1
孤荷凌寒自学python第六十二天学习mongoDB的基本操作并进行简单封装1 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第八天. 今天开始学习mongoDB的简单操作, ...
- 简单封装mongodb
首先安装mongodb npm i mongodb --save 简单封装,在modules目录下新建db.js var MongoClient=require('mongodb').MongoCl ...
随机推荐
- node,Yeoman,Bower,Grunt的简介及安装
作为前端,基本的html,css,js已经不太够用了,所以要学习一些前端自动化工具,来提高我们的生产力 1.NodeJS 先安装NodeJS,直接去官网,下载最新的版本,一定要最新的版本,这样会避免很 ...
- 使用Tenorshare iCareFone for mac为iPhone做系统修复
tenorshare icarefonemac中文版采用一键式方法来保护,修理,清洁,优化并最终加快您的iPhone,iPad和iPod的速度.它可以帮助您轻松解决所有iOS问题,并让您的iPhone ...
- 博客六--Tensorflow卷积神经网络的自主搭建
本人较懒也很忙,所以就不重复工作.连接我的开源中国博客查询:https://my.oschina.net/u/3770644/blog/3042523
- JavaSE 集合类HashSet保证自定义对象唯一性
首先我们自定义Person类,只有姓名和年龄两个属性 class Person{ private String name ; private int age ; public Person(Strin ...
- Vue的双向数据绑定
最简单的实现v-model数据绑定,只需要在一个组件里面有个props,加上一个value,然后当组件要去修改数据的时候, $emit一个input事件,并且把新的值传出去.这就实现了Vue里面的数据 ...
- 【此处有干货~】jmeter+ant+jenkins持续集成配置及过程中问题解决思路
本人是一枚工作近三年的小测试,大学正好专业为软件测试,在工作中用到最多的是功能测试.接口测试.压力测试.偶尔会涉及到性能测试......(小白,很多观念技术跟大佬差距太大,勿喷) 在接口测试过程当中, ...
- 解决Xcode8模拟器无法删除应用的问题
关闭模拟器的3DTouch.Hardware →Touch Pressure→Use Trackpad Force.
- FFMPEG增加和提取字幕流
转自 https://www.cnblogs.com/satng/p/5514683.html 防抽复制一遍 增加字幕流ffmpeg -i video.avi -i sub.ass -map 0:0 ...
- [转]数据库中间件 MyCAT源码分析——跨库两表Join
1. 概述 2. 主流程 3. ShareJoin 3.1 JoinParser 3.2 ShareJoin.processSQL(...) 3.3 BatchSQLJob 3.4 ShareDBJo ...
- CodeSampler DX9 Full-screen initialization
D3D新手,请轻拍. 最近在学CodeSampler上的DX9范例.编译环境是VS2012.搭编译环境用了一两天,另行开文吐槽(有时间的话). 本文讲讲Full-screen initializati ...