英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论