我对 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/