MongoDB 如何处理并发更新?
我开始在工作中使用 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.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MongoDB 使用进程范围的写锁来保证一次只能执行一个写操作(更新/插入/删除)。因此,它会自动解决并发问题,因为根本不允许写入并发。
如果 4 个线程尝试更新操作,其中一个线程将获取写锁,进行更新并释放锁。之后,剩下的 3 个中的一个将获取锁,进行更新等。
只有当您的操作无法包装在单个写入操作中时,并发才会发挥作用。请注意,对于最常见的用例(查找文档、更新它并原子地获取新版本),MongoDB 提供了“findAndModify”命令来执行此操作:http://www.mongodb.org/display/DOCS/findAndModify+Command
更新:现在锁定更加精细。
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.
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.
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.
使用 修饰符操作:
$inc $set $unset $push $pushAll $addToSet $pop $pull $pullAll $rename $bit
所有这些都是原子的。
Use modifier operations:
$inc $set $unset $push $pushAll $addToSet $pop $pull $pullAll $rename $bit
all of them are atomic.