MongoDB 中的 findAndModify 和 update 有什么区别? [英] What's the difference between findAndModify and update in MongoDB?

查看:39
本文介绍了MongoDB 中的 findAndModify 和 update 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 MongoDB 中的 findAndModify 方法有点困惑.它与 update 方法相比有什么优势?对我来说,它似乎只是先返回项目,然后再更新它.但是为什么我需要先退货?我阅读了MongoDB:权威指南,它说它对于操作队列和执行其他需要 get-and-set 样式原子性的操作非常方便.但我不明白它是如何实现这一点的.有人可以向我解释一下吗?

I'm a little bit confused by the findAndModify method in MongoDB. What's the advantage of it over the update method? For me, it seems that it just returns the item first and then updates it. But why do I need to return the item first? I read the MongoDB: the definitive guide and it says that it is handy for manipulating queues and performing other operations that need get-and-set style atomicity. But I didn't understand how it achieves this. Can somebody explain this to me?

推荐答案

如果您获取一个项目然后更新它,在这两个步骤之间可能会有另一个线程进行更新.如果您先更新一个项目,然后再获取它,那么中间可能会有另一个更新,您将获得与您更新的项目不同的项目.

If you fetch an item and then update it, there may be an update by another thread between those two steps. If you update an item first and then fetch it, there may be another update in-between and you will get back a different item than what you updated.

以原子方式"执行此操作意味着您可以保证取回与正在更新的项目完全相同的项目 - 即在此期间不会发生其他操作.

Doing it "atomically" means you are guaranteed that you are getting back the exact same item you are updating - i.e. no other operation can happen in between.

这篇关于MongoDB 中的 findAndModify 和 update 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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