MongoDB 多次更新隔离

标签 mongodb

我对 MongoDB 更新的工作方式感到困惑。

在以下文档中:https://docs.mongodb.com/manual/core/write-operations-atomicity/说:

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.

When a single write operation modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic and other operations may interleave.

我猜这意味着:如果我正在更新文档的所有字段,我将看不到部分更新:

  • 如果我在更新前得到文档,我会看到它没有任何变化
  • 如果我在更新后得到文档,我会看到它的所有更改

对于多个元素,每个文档都会发生相同的行为。我想我们可以说每个文档更新都有一个事务,而不是所有文档更新都有一个大事务。

但是假设在多次更新上有很多文档,并且需要一段时间才能更新所有这些文档。更新期间其他线程的查询会发生什么情况?

  • 他们会看到旧版本吗?或者他们将被阻止直到更新完成?
  • 在这次大更新期间可以对相同文档进行其他更新吗?如果是这样,这个中间更新是否可以从大更新中排除一些文档?

最佳答案

They will see the old version? Or they will be blocked until the update finishes?

我猜其他线程可能会看到文档的旧版本或新版本,这取决于他们是在更新完成之前还是之后查询文档,但他们永远不会看到文档的部分更新(即一个字段已更改另一个没有改变)。

Other updates to same documents are possible during this big update? If so, could this intermediate update exclude some document from the big update?

不是大更新或小更新,而是考虑 2 个线程对同一个文档进行更新。线程 1 设置字段 {a:1, b:2},线程 2 设置字段 {b:3, c:4}。如果原始文档是 {a:0, b:0, c:0} 那么我们可以有两种情况:

更新 1 在更新 2 之前执行: 该文档最终将是 {a:1, b:3, c:4}

更新 2 在更新 1 之前执行: 该文档最终将是 {a:1, b:2, c:4}

关于MongoDB 多次更新隔离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49925863/

相关文章:

mongodb - 如何检查数组字段是否是 MongoDB 中另一个数组的一部分?

mongodb - Spring数据MongoDb : MappingMongoConverter remove _class

mongodb - 将 robomongo 连接到 mongoDB docker 容器

javascript - javascript Node.js 的复杂性?

mongodb - 如何使用 MongoRegex(MongoDB C# 驱动程序)

node.js - 如何在不使用排序的情况下检索 mongodb-mongoose 中最近添加的文档?

javascript - 在 Mongoose 中使用 Multer 将文件存储到 MongoDB

javascript - 如何按 Meteor 中计算的属性/虚拟属性排序?

mongodb - 在 MongoDB 3.0 中正确设置只读用户?

c# - MongoDB 和 C#,如何按星期比较