how can I findAndModify one record in mongodb with golang?

huangapple go评论107阅读模式
英文:

how can I findAndModify one record in mongodb with golang?

问题

我想要这样的操作:

  1. 在MongoDB中找到一条记录 old_record
  2. 将该记录更新为 new_record
  3. 返回 old_record

我写的代码如下:

ret = nil
// 首先,找到对象
obj := &orm.QuerySetObj{}
err2 := this.querySetCollection.With(session).Find(objKey).One(obj)
if nil != err2 {
    this.logger.Println("找到对象时出错")
    return
}

ret = obj

// 然后,更新该对象
obj.updateTime = time.Now().Unix()
err3 := this.querySetCollection.With(session).Upsert(objKey, obj)
if nil != err3 {
    this.logger.Println("更新对象时出错")
    return
}

return

但是,我认为 findupdate 应该是一个原子操作,所以我的代码不安全。

如何在一个原子操作中完成这个操作?

英文:

I want something like this:

  1. find one record in mongo db old_record
  2. update this record to new_record
  3. return old_record

I write code like this:

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

but, I think find and update should be an atomic operation, so my code is not safe.

how can I do this in an atomic operation

答案1

得分: 16

这里使用的方法是.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)

其中doc是找到的文档,它的状态取决于Change参数中的ReturnNew的值,当你想要原始文档时,它的值为false

基本上,所有的参数都与.findAndModify()的形式相同。

英文:

The method here is .Apply() which takes a Change type and returns ChangeInfo.

Direct example in the documentation:

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)

Where doc is document that is found, and it's state depending on the value of ReturnNew in the Change arguments, being false where you want the original document.

Basically all arguments are in the same form as with .findAndModify()

huangapple
  • 本文由 发表于 2015年8月11日 16:52:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/31937292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定