基于mgo库包:github.com/globalsign/mgo
首先封装一个mongodb包,config是一个配置包提供数据,下面的config.Get部分的数字自行替换
package mongodb
import (
"github.com/globalsign/mgo"
"strconv"
// "labix.org/v2/mgo/bson"
)
/**
* 参考:http://www.cnblogs.com/shenguanpu/p/5318727.html
* 参考:http://www.jyguagua.com/?p=3126
*/
const (
// USER string = "user"
// MSG string = "msg"
)
var (
session *mgo.Session
ip = "127.0.0.1"
port = "27017"
databaseName = "fecshop_demo"
maxPoolSize = "10"
poolLimit = 10
)
func init(){
ip = config.Get("mgo_ip")
port = config.Get("mgo_port")
databaseName = config.Get("mgo_databaseName")
maxPoolSize = config.Get("mgo_maxPoolSize")
poolLimitStr := config.Get("mgo_poolLimit")
poolLimit, _ = strconv.Atoi(poolLimitStr)
}
func Session() *mgo.Session {
if session == nil {
var err error
session, err = mgo.Dial(ip + ":" + port + "?maxPoolSize=" + maxPoolSize)
session.SetPoolLimit(poolLimit)
if err != nil {
panic(err) // no, not really
}
}
return session.Clone()
}
// 可以指定collection,database使用配置中的值
func MC(collection string, f func(*mgo.Collection) error ) error {
session := Session()
defer func() {
session.Close()
// if err = recover(); err != nil {
// Log("M", err)
// }
}()
c := session.DB(databaseName).C(collection)
// 关于return 和 defer 执行的优先级参看:https://studygolang.com/articles/4809
return f(c)
}
// 可以指定database和collection
func MDC(dbName string, collection string, f func(*mgo.Collection) error ) error {
session := Session()
defer func() {
session.Close()
if err := recover(); err != nil {
// Log("M", err)
}
}()
c := session.DB(dbName).C(collection)
return f(c)
}
使用
1.创建mongodb索引
// 创建表索引
func createIndex(dateStr string, websiteId string) error{
dbName := helper.GetTraceDbNameByDate(dateStr)
collName := helper.GetTraceDataCollName(websiteId)
err := mongodb.MDC(dbName, collName, func(coll *mgo.Collection) error {
var err error
// 下面的每一个子项,就是一个索引。
mgoIndex := [][]string{
[]string{"order.invoice"},
[]string{"uuid", "_id"},
[]string{"ip"},
[]string{"uuid", "service_timestamp"},
}
for i:=0; i<len(mgoIndex); i++ {
index := mgo.Index{
Key: mgoIndex[i],
// Unique: true,
// DropDups: true,
Background: true, // See notes.
// Sparse: true,
}
err = coll.EnsureIndex(index)
if err != nil {
return err
}
}
// lastIndexes, err := coll.Indexes() // 查看表索引
// if err != nil {
// return err
// }
// log.Println(lastIndexes)
return err
})
return err
}
2.保存数据
type TraceInfo struct{
Id_ bson.ObjectId `form:"_id" json:"_id" bson:"_id"`
Uuid string `binding:"required" form:"uuid" json:"uuid" bson:"uuid"`
... // 定义其他
}
err = mongodb.MDC(dbName, collName, func(coll *mgo.Collection) error {
traceInfo.Id_ = bson.NewObjectId()
err := coll.Insert(traceInfo)
return err
})
if err != nil {
c.AbortWithStatusJSON(http.StatusOK, util.BuildFailResult(err.Error()))
return
}
update
package fec
import(
...
"github.com/gin-gonic/gin"
"net/http"
"errors"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
)
err = mongodb.MDC(dbName, collName, func(coll *mgo.Collection) error {
// 如果传递了订单,那么将订单保存到这个变量中
// var orderInfo OrderInfo
var err error
// 如果是成功订单,那么只更新订单的支付状态,其他的不变
if traceApiInfo.PaymentSuccessOrder.Invoice != "" {
invoice := traceApiInfo.PaymentSuccessOrder.Invoice
payment_status := traceApiInfo.PaymentSuccessOrder.PaymentStatus
if invoice == "" {
return errors.New("invoice can not empty")
}
// invoice两个作为条件查询
selector := bson.M{"order.invoice": invoice}
updateData := bson.M{"$set": bson.M{"order.payment_status": payment_status}}
err = coll.Update(selector, updateData)
return err
}
// 进行赋值。 // bsonObjectID := bson.ObjectIdHex("573ce4451e02f4bae78788aa")
})
if err != nil {
c.AbortWithStatusJSON(http.StatusOK, util.BuildFailResult(err.Error()))
return
}