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?
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} }
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With