rog*_*ger 6 atomic go mongodb findandmodify
我想要这样的东西:
old_recordnew_recordold_record我写这样的代码:
ret = nil
// First, Find the obj
obj := &orm.QuerySetObj{}
err2 := this.querySetCollection.With(session).Find(objKey).One(obj)
if nil != err2 {
this.logger.Println("Error find obj")
return
}
ret = obj
// Then, update this obj
obj.updateTime = time.Now().Unix()
err3 := this.querySetCollection.With(session).Upsert(objKey, obj)
if nil != err3 {
this.logger.Println("Error update obj")
return
}
return
Run Code Online (Sandbox Code Playgroud)
但是,我想find和update应该是一个atomic操作,所以我的代码是不是安全.
我怎么能在原子操作中做到这一点
Bla*_*ven 15
这里的方法是.Apply()采用Change类型并返回ChangeInfo.
文档中的直接示例:
change := mgo.Change{
Update: bson.M{"$inc": bson.M{"n": 1}},
ReturnNew: false,
}
info, err = col.Find(M{"_id": id}).Apply(change, &doc)
fmt.Println(doc.N)
Run Code Online (Sandbox Code Playgroud)
哪里doc是被发现的文件,而且它依赖于该值的状态ReturnNew在Change争论,是false要将原来的文档.
基本上所有参数的形式都与之相同 .findAndModify()