gpt4 book ai didi

mongodb - 在 MongoDB 中锁定文档

转载 作者:可可西里 更新时间:2023-11-01 10:01:25 25 4
gpt4 key购买 nike

我在网络应用程序中使用 pymongo,并希望执行以下形式的操作:

doc = collection.find(document)
doc.array1.append('foo')
for(y in doc.array2): <do things with y>
doc.array2 = filter(lambda x: ..., doc.array2)
doc.x = len(doc.array2)
collection.save(doc)

有什么简单的方法可以处理处理同一个文档的多个请求,并防止一个请求破坏另一个的结果/因为它正在编辑一个陈旧的版本而变得无效?

最佳答案

查看 mongodb 文档中关于 Atomic Operations 的部分

您可能感兴趣的部分是有关更新(如果它仍然是最新的)的部分。

  1. Fetch the object.
  2. Modify the object locally.
  3. Send an update request that says "update the object to this new value if it still matches its old value".

Should the operation fail, we might then want to try again from step 1.

当您有许多操作要执行并且您希望避免持有数据库锁时,可以使用这种方法。他们还在该文档中说明了他们通常是如何反对持有锁的。

关于mongodb - 在 MongoDB 中锁定文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11496763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com