Golang 對MongoDB的操做簡單封裝

Golang 對MongoDB的操做簡單封裝

使用MongoDB的Go驅動庫 mgo,對MongoDB的操做作一下簡單封裝git

初始化

  • 操做沒有用戶權限的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)github

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:要插入的數據mongodb

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:更新的操做bash

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:刪除條件ui

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:查詢到的結果spa

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()
}
複製代碼

完整的代碼請參考code

相關文章
相關標籤/搜索