简体   繁体   English

我应该如何在mongodb中处理并发?

[英]How should I handle concurrency in mongodb?

I am working on a web service that is writing data records to mongodb. 我正在将数据记录写入mongodb的Web服务上。 The service reads a document from mongodb, performs some calculations and updates the data in the document and then overwrites the document back to mongodb. 该服务从mongodb读取文档,执行一些计算并更新文档中的数据,然后将文档覆盖回mongodb。 I need to make sure that before I write the data back to mongodb, no other process has updated that document, otherwise I may experience data loss when replacing the document. 我需要确保在将数据写回到mongodb之前,没有其他进程更新过该文档,否则替换文档时可能会丢失数据。 How can I ensure data integrity like this at the application level? 如何在应用程序级别确保这样的数据完整性? Can I lock the document while performing calculations? 执行计算时可以锁定文档吗? Should I check a version number on the document before replacing the document? 在替换文档之前,我应该检查文档上的版本号吗? What are some strategies the industry uses to handle situations like this? 业界用于处理此类情况的策略有哪些? Thanks in advance 提前致谢

You can query a value in the document to be updated as part of your call to update() to check that the document is still in a state that you expect, and confirm that no-one else updated it since you last read the document. 您可以在对update()的调用中查询要更新的文档中的值,以检查该文档是否仍处于期望的状态,并确认自上次阅读文档以来没有其他人对其进行过更新。 Similar to an optimistic lock approach. 类似于乐观锁定方法。 See https://docs.mongodb.com/manual/core/write-operations-atomicity/#concurrency-control 参见https://docs.mongodb.com/manual/core/write-operations-atomicity/#concurrency-control

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM