文章目录
golang常用库之-mgo.v2包、MongoDB官方go-mongo-driver包、七牛Qmgo包 | go操作mongodb
一、【不推荐】mgo.v2包
- mgo.v2包
官网:http://labix.org/mgo
引用包: gopkg.in/mgo.v2
mgo.v2包,已经跟不上mongo版本了,很早之前就停止维护了,后面会有更多的兼容性问题。不支持最新版本的mongo(5.x以上)!
【推荐】github.com/vinllen/mgo
国人fork的一个mgo版本,github.com/vinllen/mgo 这个库支持新版本,而且不用改之前mgo代码。
该fork 进行了一些改进,添加了一些新功能,但大多用于改进性能和错误修复的变化。
使用mgo整理思路
- 创建 DialInfo 结构体实例,它包含与MongoDB群集建立会话的选项
- 调用 mgo.DialWithInfo 建立新会话,返回会话实例
- 在程序启动时,我创建了一个主 mgo.Session,然后,对于每个处理的请求,我复制主会话
session.Copy()
并在完成后关闭它。
伪代码示例:
var dialInfo *mgo.DialInfo
//dialInfo 实例各种配置赋值
dialInfo.Timeout = time.Second * 5
m.dbSession, err = mgo.DialWithInfo(dialInfo)
sess := m.dbSession.Copy()
defer sess.Close()
err = m.dbSession.DB("").C(colName).Create(&mgo.CollectionInfo{
Capped: true, MaxBytes: colCapMaxSizeBytes})
注意:如果Capped是true,那么当collection 满了。必须设置MaxBytes定义集合wraps 的大小。
MaxDocs是可选的,可以定义wraps的文档数,但仍需要设置MaxBytes。
做插入文档操作,使用的是Insert方法,如下:
伪代码
sess := m.dbSession.Copy()
defer sess.Close()
sess.DB("").C(collectionName).Insert(dataSet...)
// Insert 集合中插入一个或多个文档
func (c *Collection) Insert(docs …interface{}) error {
mgo 和核心结构体是 mgo.Session
// mgo.v3: Drop Strong mode, suffix all modes with "Mode".
// When changing the Session type, check if newSession and copySession
// need to be updated too.
// Session represents a communication session with the database.
//
// All Session methods are concurrency-safe and may be called from multiple
// goroutines. In all session modes but Eventual, using the session from
// multiple goroutines will cause them to share the same underlying socket.
// See the documentation on Session.SetMode for more details.
type Session struct {
defaultdb string
sourcedb string
syncTimeout time.Duration
sockTimeout time.Duration
poolLimit int
poolTimeout time.Duration
consistency Mode
creds []Credential
dialCred *Credential
safeOp *queryOp
mgoCluster *mongoCluster
slaveSocket *mongoSocket
masterSocket *mongoSocket
m sync.RWMutex
queryConfig query
bypassValidation bool
slaveOk bool
}
三、MongoDB官方 go-mongo-driver。
go-mongo-driver 功能抽象没有 mgo 那么高级,用起来很零碎。
四、【推荐】七牛Qmgo包
什么是qiniu/qmgo包
github: https://github.com/qiniu/qmgo
七牛研发团队开源Go语言的MongoDB driver Qmgo。
它基于MongoDB官方 mongodb/mongo-go-driver 实现,但是有着更好的易用性,设计上参考了老牌的driver Mgo: go-mgo/mgo(比如Mgo的链式调用)。
相对于其他库,我发现这个库更新算是比较频繁,而且是以公司名义开源,可以试试~
示例查看官方demo即可: https://github.com/qiniu/qmgo/blob/master/README_ZH.md
入库mongodb demo
package main
import (
"context"
"fmt"
"github.com/qiniu/qmgo"
)
type UserInfo struct {
Name string `bson:"name"`
Age uint16 `bson:"age"`
Weight uint32 `bson:"weight"`
}
func main() {
ctx := context.Background()
// Database:库名 Coll:集合名
cli, err := qmgo.Open(ctx, &qmgo.Config{
Uri: "mongodb://127.0.0.1:27017", Database: "mongo_1", Coll: "collection_1"})
defer func() {
if err = cli.Close(ctx); err != nil {
panic(err)
}
}()
cli.EnsureIndexes(ctx, []string{
}, []string{
"age", "name,weight"})
var userInfo = UserInfo{
Name: "xm",
Age: 7,
Weight: 40,
}
// insert one document
result, err := cli.InsertOne(ctx, userInfo)
fmt.Println("result", result)
// find one document
//one := UserInfo{}
//err = cli.Find(ctx, bson.M{"name": userInfo.Name}).One(&one)
//err = cli.Remove(ctx, bson.M{"age": 7})
}