原子更新多个文档并返回 [英] ATOMICally update multiple documents AND return them
问题描述
在MongoDB
中,我正在寻找一种方法来自动更新多个文档并在一次调用中返回所有已更新的文档.
In MongoDB
, I'm looking for a way to ATOMICally update multiple documents and return all of the updated documents in a single call.
我们可以在MongoDB
中执行以下所有操作:
We can do all of the following in MongoDB
:
- 以原子方式更新一个文档并返回更新的文档:
findAndModify
或findOneAndUpdate
- 以原子方式更新多个文档:
update(...{multi: true}
或updateMany
- 查询并返回多个文档:
find
- Atomically update one document and return the updated document:
findAndModify
orfindOneAndUpdate
- Atomically update multiple documents:
update(...{multi: true}
orupdateMany
- Query and return multiple documents:
find
我还没有一种方法可以更新多个文档并在一次调用中将它们全部返回.有办法吗?我正在使用Mongoose
作为查询包.
I haven't fond a way to update multiple documents and return them all in one call. Is there a way? I'm using Mongoose
as the querying package.
推荐答案
以原子方式更新多个文档:
update(...{multi: true}
或updateMany
很遗憾,这是错误的:
However, you can simulate a transaction to atomically update multiple documents by "using a two-phase commit approach" which is described in detail there.
You may also look at the $isolated
operator, which "prevents a write operation that affects multiple documents from yielding to other reads or writes once the first document is written" but it "does not provide "all-or-nothing" atomicity for write operations"
作为总结,不可能在mongodb级别上(也不在驱动程序上),但是您可以在应用程序级别上对其进行仿真,因此返回您所需的内容.
As a summary, it is not possible at mongodb level (nor the driver), but you can simulate it at your application level therefore return what you need.
这篇关于原子更新多个文档并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!