Golang对MongoDB数据库的操作简单封装教程
2018-07-05 10:53
746 查看
Golang 对MongoDB的操作简单封装
使用MongoDB的Go驱动库 mgo,对MongoDB的操作做一下简单封装
mgo(音mango)是MongoDB的Go语言驱动,它用基于Go语法的简单API实现了丰富的特性,并经过良好测试。
初始化
操作没有用户权限的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() }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
您可能感兴趣的文章:
- python连接mongodb操作数据示例(mongodb数据库配置类)
- php操作mongodb封装类与用法实例
- MongoDB基础命令以及操作示例详解
- Python常见MongoDB数据库操作实例总结
- Python使用pymongo模块操作MongoDB的方法示例
- PHP操作Mongodb封装类完整实例
- PHP mongodb操作类定义与用法示例【适合mongodb2.x和mongodb3.x】
- Python操作mongodb数据库进行模糊查询操作示例
- Python操作mongodb的9个步骤
- 关于MongoDB索引管理-索引的创建、查看、删除操作详解
- Mongodb基本操作与Python连接mongodb并进行基础操作的方法
相关文章推荐
- 对JDBC操作数据库的简单封装
- python 操作oracle 简单封装
- UICollectionView实现的图片的多选效果(本人已封装好,简单操作)
- 史上最简单的 MySQL 教程(二十一)「数据的高级操作 之 蠕虫复制」
- golang-redis之set类型简单操作
- 简单封装JavaScript Date对象操作
- python操作word【简单封装】
- 封装一个简单的池操作
- 史上最简单的 MySQL 教程(二十四)「数据的高级操作 之 查询(中)」
- php简单封装了一些常用JS操作
- node.js零基础详细教程(6):mongodb数据库操作 以及导入导出
- 史上最简单的 MySQL 教程(二十二)「数据的高级操作 之 更新 & 删除」
- golang 文件简单操作
- Python Sql数据库增删改查操作简单封装
- Android数据库操作的简单封装
- 史上最简单的 MySQL 教程(六)「SQL 基本操作 之 数据操作」
- Golang1.7.3简单的rsa加密封装
- MongoDB数据库的MapReduce简单操作(转)
- ADO.NET 操作数据库 --- 01 简单封装
- Windows手动搭建邮箱服务器教程,操作简单易上手