Question

The Mongo documentation on atomicity and isolation is a tad vague and slightly confusing. I have this document structure and I want to ensure mongo will handle updates while isolating updated from different users.

Assume a collection of product discount offers. When a user redeems an offer, the offers_redeemed field is incremented. The max_allowed_redemptions field controls how many times an offer can be redeemed.

{ 
     offer_id: 99,
     description: “Save 25% on Overstock.com…” 
     max_allowed_redemptions: 10,
     offers_redeemed: 3
}

I tested this using findAndModify and it appears to work by updating the offer only if another redemption would be less than or equal to the max allowed; I want to know if this is the correct way to do it and if this would work in a multi user, sharded environment. Is there a scenario where an update to offers_redeemed would force it to exceed max_allowed_redemptions ? , obviously, that would corrupt the record so we need to avoid it.

db.offer.findAndModify({
   query:{ offer_id: 99, $where: “this.offers_redeemed + 1 <= this.max_allowed_redemptions”},
   update: {$inc: {offers_redeemed: 1},
   new: true })
Was it helpful?

Solution

First as the documentation very clearly says

If you don't need to return the document, you can use Update (which can affect multiple documents, as well).

Second, watch the Update if Current strategy on the atomic page. It clearly shows that if the condition applies then the update happens and nothing can come between the two.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top