MongoDB如何处理并发更新? [英] How does MongoDB deal with concurrent updates?
问题描述
到目前为止,我开始在工作中使用MongoDB. 我想知道MongoDB如何处理并发更新? 我已经读过MongoDB中没有锁定功能,所以我想知道处理此问题的常用方法是什么.
I started to use MongoDB at work so far so good. I was wondering though how does MongoDB deal with concurrent updates ? I've read that there is no locking feature in MongoDB so I was wondering what is the the common practice to deal with this.
谢谢.
推荐答案
MongoDB使用了进程范围的写锁定,以确保一次只能执行一个写操作(更新/插入/删除).这样,由于完全不允许写入并发,因此它可以自动解决并发问题.
MongoDB used a process wide write lock to guarantee that only one write operation (update/insert/remove) can be performed at a time. As such it automatically solves concurrency issues since write concurrency simply isn't allowed.
如果有4个线程尝试执行更新操作,则其中一个将获得写锁,进行更新并释放该锁.之后,其余3个中的1个将抓住该锁,进行更新等.
If 4 threads attempt an update operation one of them will take the write lock, do its update and release the lock. After that one of the remaining 3 will grab the lock, do its update, etc.
仅当您的操作不能包装在单个写操作中时,并发才起作用.请注意,对于最常见的用例(查找文档,对其进行更新并以原子方式获取新版本),MongoDB提供了"findAndModify"命令,该命令可以做到:
Concurrency only comes into play if your operation cannot be wrapped in a single write operation. Note that for the most common usecase (find a doc, update it and grab the new version atomically) MongoDB offers the "findAndModify" command which does just that : http://www.mongodb.org/display/DOCS/findAndModify+Command
更新:这些天锁定更加精细.
UPDATE : Locking is more granular these days.
这篇关于MongoDB如何处理并发更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!