简体   繁体   中英

How should I handle concurrency in mongodb?

I am working on a web service that is writing data records to mongodb. 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. 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. 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. Similar to an optimistic lock approach. See https://docs.mongodb.com/manual/core/write-operations-atomicity/#concurrency-control

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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