Race conditions in Mongo and most efficient patterns?
I'm getting started with Mongo and I'm wondering: what's the best way to handle race conditions in Mongo?
For example, if I have a document with a field called version set at 1 and User A updates it to version 2, when User B tries to update it from version 1 (the version that User B received), it should notify User B that the the record has been updated.
One solution is to use findAndMod开发者_运维百科ify
using the version field as a criteria for the query.
For example:
db.things.findAndModify({query: { version: "1"}, update: { $set: {Title: "New Title"}}})
However, the problem here is that if the version has been incremented, this will return null. The problem is that this would be indistinguishable from a record which has been deleted so a second query would have to be used to check to see if the document still exists to confirm that it's only the version that's been updated.
So that's my naive approach. I'm wondering: is there a more proper pattern for this in Mongo that would be more efficient?
This kind of concurrency has to be dealt from the client side. So what you are doing is, AFAIK, the right thing.
I think this will be the case with any database, not just Mongo.
精彩评论