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 个中的一个将获取锁,进行更新等.
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"命令,它就是这样做的:http://www.mongodb.org/display/DOCS/findAndModify+Command
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屋!