Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo: eliminating race condition on conditional update

Is it possible to insert or update an item in a collection ONLY IF a condition is met, without race conditions?

For example, let's say I had a collection with a timestamp field and a temperature field. Would it be possible to update a particular item only if the timestamp is at least one hour old? I know I could (step 1) check the timestamp with one call, then (step 2) do some math to see if the timestamp is more than an hour ago, and then (step 3) update the item in the collection if so.

But this fails if another client updates the client while this client is running step 2. Then two updates would occur when I only wanted one.

This is not the specific case I am dealing with, but illustrates my question. If a mongo operation depends on another mongo operation, how can race conditions be addressed?

like image 328
Christopher Shroba Avatar asked Feb 11 '23 03:02

Christopher Shroba


1 Answers

What you need is findAndModify ;)

It allows to do a GET followed by an UPDATE in a single operation.

You can use a processing flag, first false and you change it when doing the findAnModify()

db.col.findAndModify({
    query: { processed: false },
    update: { $inc: { score: 1 }, $set:{processed: true} }
})
like image 88
xsenechal Avatar answered Feb 24 '23 13:02

xsenechal