英文:
How can we get the updated document in response on calling updateOne
问题
以下是我想要更新某个id的json文档:
{
"_id": "some_id",
"counter": {
"$incr": 1,
},
}
使用上述bson进行更新后,借助库(github.com/mongodb/mongo-go-driver),它将在集合中将字段counter的计数器值增加1。
如何在不再次查询或获取锁的情况下获取更新后的结果?
英文:
Below is the json document that i want to update for some id
{
"_id": "some_id",
"counter": {
"$incr": 1,
},
}
after using the above bson for update with the help of library (github.com/mongodb/mongo-go-driver) it will increment the counter value by 1 in the collection for the field counter.
How can I get the updated result without querying again, or without acquiring a lock?
答案1
得分: 2
你可以使用findOneAndUpdate
命令,并设置选项在更新执行后返回文档。
查询:
err = collection.FindOneAndUpdate(
ctx,
bson.D{}, // <- 查找块
bson.D{{
"$inc", bson.D{{ // <- 更新块
"counter", 1,
}},
}},
options.FindOneAndUpdate().SetReturnDocument(options.After), // <- 设置选项以在更新后返回文档(重要)
).Decode(&result) // <- 将文档保存到变量中
英文:
You can make use of the findOneAndUpdate
command and set option to return documents after the update is performed.
Query:
err = collection.FindOneAndUpdate(
ctx,
bson.D{}, // <- Find block
bson.D{{
"$inc", bson.D{{ // <- update block
"counter", 1,
}},
}},
options.FindOneAndUpdate().SetReturnDocument(options.After), // <- Set option to return document after update (important)
).Decode(&result) // <- Save document to variable
答案2
得分: 0
从文档中
您应该将新选项设置为true,以便在应用更新后返回文档。
Character.findOneAndUpdate(filter, update, { new: true });
英文:
From documentation
You should set the new option to true to return the document after update was applied.
Character.findOneAndUpdate(filter, update, { new: true });
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论