在MongoDB中锁定文档 [英] Locking a document in MongoDB

查看:71
本文介绍了在MongoDB中锁定文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Web应用程序中使用pymongo,并且想要做某种形式的事情:

I'm using pymongo in a web app, and want to do something of the form:

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)

有没有一种简单的方法可以处理多个处理同一文档的请求,并防止一个文件掩盖另一个文件的结果,或者因为它正在编辑过时的版本而使该文件无效?

Is there any simple way way I can handle multiple requests dealing with the same document and prevent one from clobbering the results of another / be made invalid because it's editing a stale version?

推荐答案

看看您可能会感兴趣的部分是有关更新的部分,如果该更新仍然是最新的.

The section that might be of interest to you is the part about updating if it is still current.

  1. 获取对象.
  2. 在本地修改对象.
  3. 发送一个更新请求,内容为如果对象仍旧与其旧值匹配,则将该对象更新为该新值".
  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".

如果操作失败,我们可能要从步骤1开始重试.

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

当您要执行许多操作并且想要避免对数据库保持锁定时,这是一种方法.他们还在该文档中指出了他们通常反对持有锁的方式.

This is the approach for when you have a number of operations to perform and you want to avoid holding a lock on the database. They also state in that doc how they are generally against holding a lock.

这篇关于在MongoDB中锁定文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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