将mgo的reduce、update和find操作合并为一次查询。

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

mgo - reduce update and find to one query only

问题

我发现自己需要编写两个数据库查询,我想知道是否可能将其减少为一个查询。

我正在更新一个文档,然后在数据库中再次查找该文档。是否可能在更新查询的响应中同时更新并获取完整的更新文档?这样可以避免对数据库的额外调用。

我应该解释一下,我保存的文档不会是一个完整的文档,这就是为什么我需要从数据库中检索它以获取所有字段的原因。

英文:

I find myself having to write two db queries and I would like to know whether it's possible to reduce to one.

I am updating a document and then finding the document again in the database. Is it possible to update and receive the full updated document in the response of the update query? This would save a call to the db.

I should explain that the document I'm saving won't be a complete document which is why I'm having to retrieve it from the database to get all the fields.

答案1

得分: 1

是的,这是可能的。请查看Query.Apply方法的文档,该方法运行findAndModify MongoDB命令。

直接从文档中,以下示例会增加一个计数器并打印其新值:

change := mgo.Change{
        Update: bson.M{"$inc": bson.M{"n": 1}},
        ReturnNew: true,
}
info, err = col.Find(M{"_id": id}).Apply(change, &doc)
fmt.Println(doc.N)
英文:

Yes, it is possible. Please have a look at the documentation of the Query.Apply method, which runs the findAndModify MongoDB command.

Straight from the documentation, this example increments a counter and prints its new value:

change := mgo.Change{
        Update: bson.M{"$inc": bson.M{"n": 1}},
        ReturnNew: true,
}
info, err = col.Find(M{"_id": id}).Apply(change, &doc)
fmt.Println(doc.N)

huangapple
  • 本文由 发表于 2015年9月18日 00:04:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/32635007.html
匿名

发表评论

匿名网友

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

确定