Golang對(duì)MongoDB數(shù)據(jù)庫(kù)的操作簡(jiǎn)單封裝教程
前言
Golang 對(duì)MongoDB的操作簡(jiǎn)單封裝
使用MongoDB的Go驅(qū)動(dòng)庫(kù) mgo,對(duì)MongoDB的操作做一下簡(jiǎn)單封裝
mgo(音mango)是MongoDB的Go語(yǔ)言驅(qū)動(dòng),它用基于Go語(yǔ)法的簡(jiǎn)單API實(shí)現(xiàn)了豐富的特性,并經(jīng)過(guò)良好測(cè)試。
初始化
操作沒(méi)有用戶(hù)權(quán)限的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設(shè)置了用戶(hù)權(quán)限需要使用下面的方法操作
func init() {
dialInfo := &mgo.DialInfo{
Addrs: []string{dbhost}, //數(shù)據(jù)庫(kù)地址 dbhost: mongodb://user@123456:127.0.0.1:27017
Timeout: timeout, // 連接超時(shí)時(shí)間 timeout: 60 * time.Second
Source: authdb, // 設(shè)置權(quán)限的數(shù)據(jù)庫(kù) authdb: admin
Username: authuser, // 設(shè)置的用戶(hù)名 authuser: user
Password: authpass, // 設(shè)置的密碼 authpass: 123456
PoolLimit: poollimit, // 連接池的數(shù)量 poollimit: 100
}
s, err := mgo.DialWithInfo(dialInfo)
if err != nil {
log.Fatalf("Create Session: %s\n", err)
}
globalS = s
}
連接具體的數(shù)據(jù)和文檔
每一次操作都copy一份 Session,避免每次創(chuàng)建Session,導(dǎo)致連接數(shù)量超過(guò)設(shè)置的最大值
獲取文檔對(duì)象 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
}
插入數(shù)據(jù)
每次操作之后都要主動(dòng)關(guān)閉 Session defer Session.Close()
db:操作的數(shù)據(jù)庫(kù)
collection:操作的文檔(表)
doc:要插入的數(shù)據(jù)
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: "標(biāo)題",
Des: "博客描述信息",
Content: "博客的內(nèi)容信息",
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)
查詢(xún)數(shù)據(jù)
db:操作的數(shù)據(jù)庫(kù)
collection:操作的文檔(表)
query:查詢(xún)條件
selector:需要過(guò)濾的數(shù)據(jù)(projection)
result:查詢(xún)到的結(jié)果
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 查詢(xún)title="標(biāo)題",并且返回結(jié)果中去除`_id`字段
var result Data
err = db.FindOne(database, collection, bson.M{"title": "標(biāo)題"}, bson.M{"_id":0}, &result)
更新數(shù)據(jù)
db:操作的數(shù)據(jù)庫(kù)
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)
}
//更新,如果不存在就插入一個(gè)新的數(shù)據(jù) `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": "更新標(biāo)題"}})
刪除數(shù)據(jù)
db:操作的數(shù)據(jù)庫(kù)
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"})
分頁(yè)查詢(xún)
db:操作的數(shù)據(jù)庫(kù)
collection:操作的文檔(表)
page:當(dāng)前頁(yè)面
limit:每頁(yè)的數(shù)量值
query:查詢(xún)條件
selector:需要過(guò)濾的數(shù)據(jù)(projection)
result:查詢(xún)到的結(jié)果
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()
}
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
詳解如何利用GORM實(shí)現(xiàn)MySQL事務(wù)
為了確保數(shù)據(jù)一致性,在項(xiàng)目中會(huì)經(jīng)常用到事務(wù)處理,對(duì)于MySQL事務(wù)相信大家應(yīng)該都不陌生。這篇文章主要總結(jié)一下在Go語(yǔ)言中Gorm是如何實(shí)現(xiàn)事務(wù)的;感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助2022-09-09
深入了解Go的interface{}底層原理實(shí)現(xiàn)
本文主要介紹了Go的interface{}底層原理實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
Go語(yǔ)言開(kāi)發(fā)區(qū)塊鏈只需180行代碼(推薦)
這篇文章主要介紹了Go語(yǔ)言開(kāi)發(fā)區(qū)塊鏈只需180行代碼,文章中將不會(huì)涉及工作量證明算法(PoW)以及權(quán)益證明算法(PoS)這類(lèi)的共識(shí)算法。需要的朋友可以參考下2018-05-05
gorm+gin實(shí)現(xiàn)restful分頁(yè)接口的實(shí)踐
本文主要介紹了gorm+gin實(shí)現(xiàn)restful分頁(yè)接口的實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12

