go mgo包 简单封装 mongodb 数据库驱动

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
", err)
	//}
	//globalS = s
	s, err := mgo.Dial("127.0.0.1:27017")
	if err != nil {
		log.Fatalf("Create Session: %s
", 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()
}
原文地址:https://www.cnblogs.com/niuben/p/14664343.html