原子更新多个文档并返回 [英] ATOMICally update multiple documents AND return them

查看:69
本文介绍了原子更新多个文档并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

  • 以原子方式更新一个文档并返回更新的文档:findAndModifyfindOneAndUpdate
  • 以原子方式更新多个文档:update(...{multi: true}updateMany
  • 查询并返回多个文档:find
  • Atomically update one document and return the updated document: findAndModify or findOneAndUpdate
  • Atomically update multiple documents: update(...{multi: true} or updateMany
  • 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

很遗憾,这是错误的:

在MongoDB中,写操作,例如db.collection.update(), db.collection.findAndModify(),db.collection.remove()是 atomic on 单个文档的级别.

In MongoDB, write operations, e.g. db.collection.update(), db.collection.findAndModify(), db.collection.remove(), are atomic on the level of a single document.


在MongoDB中,写操作是 atomic on单个级别 文档,即使该操作修改了多个嵌入式文档 在一个文档中.

In MongoDB, a write operation is atomic on the level of a single document, even if the operation modifies multiple embedded documents within a single document.

但是,您可以通过 ,在此进行了详细说明.

However, you can simulate a transaction to atomically update multiple documents by "using a two-phase commit approach" which is described in detail there.

您还可以查看$isolated运算符,该运算符 但它

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆