不可能锁定mongodb文档.如果需要我该怎么办? [英] It's not possible to lock a mongodb document. What if I need to?

查看:112
本文介绍了不可能锁定mongodb文档.如果需要我该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我无法锁定单个mongodb文档,实际上也无法锁定集合.

I know that I can't lock a single mongodb document, in fact there is no way to lock a collection either.

但是,在这种情况下,我认为我需要某种方法来防止多个线程(或过程,这并不重要)修改文档.这是我的情况.

However, I've got this scenario, where I think I need some way to prevent more than one thread (or process, it's not important) from modifying a document. Here's my scenario.

我有一个包含类型A的对象的集合.我有一些代码来检索类型A的文档,在数组中添加一个元素作为文档的属性(a.arr.add(new Thing()),然后保存回该文档到mongodb.此代码是并行的,我的应用程序中的多个线程可以执行这些操作,并且目前尚无办法阻止线程在同一文档上并行执行这些操作.这很糟糕,因为其中一个线程可能会覆盖另一个线程的工作.

I have a collection that contains object of type A. I have some code that retrieve a document of type A, add an element in an array that is a property of the document (a.arr.add(new Thing()) and then save back the document to mongodb. This code is parallel, multiple threads in my applications can do theses operations and for now there is no way to prevent to threads from doing theses operations in parallel on the same document. This is bad because one of the threads could overwrite the works of the other.

我确实使用存储库模式来抽象化对mongodb集合的访问,因此我在处置时仅具有CRUD操作.

I do use the repository pattern to abstract the access to the mongodb collection, so I only have CRUDs operations at my disposition.

现在我考虑一下,也许这是存储库模式的局限性,而不是导致我麻烦的mongodb的局限性.无论如何,如何使此代码线程安全"?我想有一个众所周知的解决方案,但是对于mongodb和存储库模式来说,我是陌生的.

Now that I think about it, maybe it's a limitation of the repository pattern and not a limitation of mongodb that is causing me troubles. Anyway, how can I make this code "thread safe"? I guess there's a well known solution to this problem, but being new to mongodb and the repository pattern, I don't immediately sees it.

谢谢

推荐答案

在进行mongodb升级时偶然发现了这个问题.与问这个问题时不同,现在mongodb支持开箱即用的文档级别锁定.

Stumbled into this question while working on mongodb upgrades. Unlike at the time this question was asked, now mongodb supports document level locking out of the box.

来自: http://docs.mongodb.org/manual/faq/concurrency/

"MongoDB中的锁有多细?

"How granular are locks in MongoDB?

在3.0版中进行了更改.

Changed in version 3.0.

从3.0版开始,MongoDB附带WiredTiger存储引擎,该引擎使用乐观并发控制来执行大多数读取和写入操作. WiredTiger仅在全局,数据库和集合级别使用意图锁.当存储引擎检测到两个操作之间存在冲突时,将引发写冲突,从而导致MongoDB透明地重试该操作."

Beginning with version 3.0, MongoDB ships with the WiredTiger storage engine, which uses optimistic concurrency control for most read and write operations. WiredTiger uses only intent locks at the global, database and collection levels. When the storage engine detects conflicts between two operations, one will incur a write conflict causing MongoDB to transparently retry that operation."

这篇关于不可能锁定mongodb文档.如果需要我该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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