golang 對mongodb的操作簡單封裝
使用mongodb
的go驅動庫 mgo,對mongodb
的操作做一下簡單封裝
初始化
var globals *mgo.session
func init
() globals = s
}複製**
連線具體的資料和文件func init
() , //資料庫位址 dbhost: mongodb:
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
globals = s
}複製**
每一次操作都copy乙份session
,避免每次建立session
,導致連線數量超過設定的最大值 獲取文件物件c := session.db(db).c(collection)
插入資料func connect(db, collection string) (*mgo.session, *mgo.collection)
複製**
每次操作之後都要主動關閉session
defer session.close()
db:操作的資料庫
collection:操作的文件(表)
doc:要插入的資料
查詢資料func insert(db, collection string, doc inte***ce{}) error
// test
data := &data
err := db.insert("test", "testmodel", data)
複製**
db:操作的資料庫
collection:操作的文件(表)
query:查詢條件
selector:需要過濾的資料(projection)
result:查詢到的結果
更新資料func findone(db, collection string, query, selector, result inte***ce{}) error
func findall(db, collection string, query, selector, result inte***ce{}) error
//test 查詢title="標題",並且返回結果中去除`_id`字段
var result data
err = db.findone(database, collection, bson.m, bson.m, &result)
複製**
db:操作的資料庫
collection:操作的文件(表)
selector:更新條件
update:更新的操作
刪除資料func update(db, collection string, selector, update inte***ce{}) error
//更新,如果不存在就插入乙個新的資料 `upsert:true`
func upsert(db, collection string, selector, update inte***ce{}) error
// `multi:true`
func updateall(db, collection string, selector, update inte***ce{}) error
//test
err = db.update(database, collection, bson.m, bson.m})
複製**
db:操作的資料庫
collection:操作的文件(表)
selector:刪除條件
分頁查詢func remove(db, collection string, selector inte***ce{}) error
func removeall(db, collection string, selector inte***ce{}) error
//test
err = db.remove(database,collection,bson.m)
複製**
db:操作的資料庫
collection:操作的文件(表)
page:當前頁面
limit:每頁的數量值
query:查詢條件
selector:需要過濾的資料(projection)
result:查詢到的結果
其他操作func findpage(db, collection string, page, limit int, query, selector, result inte***ce{}) error
複製**
完整的**請參考func isempty(db, collection string) bool
return count == 0
}func count(db, collection string, query inte***ce{}) (int, error)
複製**
python對MongoDB的操作
python連線 try conn mongoclient ip,port database conn db db為資料庫名稱 my set database tb tb為表名稱 logger.info 需要檢測的字段 format field nm all my set.estimated doc...
Golang對Redis的常用操作
redis操作package redis 獲取乙個 redis.client func newrds addr,password string db,poolsize int client clientredis,err error pong,err client.ping result if er...
Golang對excel進行處理
國慶節祝我們的祖國更加繁榮昌盛,想必大家在國慶期間也好好放鬆了一下,中秋節過節停更了一次,家裡面有孩子了,放假期間希望能好好陪陪孩子,請大家諒解。今天發一篇技術文章,幫助大家逐漸回歸到正常的工作狀態。go get github.com tealeg xlsx我們通過乙個簡單的例子看看這個包如何使用,...