In Mongo any way to do check and setting like atomic operation?

Viewed 1758

Is in Mongo any way to do check and setting like atomic operation ? I am making booking for hotels and if there is free room you can reserve, but what if two or more people want to reserve in same time. Is there anything similar to transaction in Mongo or any way to solve this problem ?

3 Answers

The answers reference findAndModify documentation. But a practical example given the OP's requirements will do justice:

const current = new ISODate();
const timeAgoBy30Minutes = new Date(current.getTime()  - 1000 * 30 ).toISOString();

db.runCommand(
  {
    findAndModify: "rooms",
    query: {
      "availability" : true,
      "lastChecked" : {
        "$lt": timeAgoBy30Minutes
      }
    },
    update: { $set: { availability: false, lastChecked:  current.toISOString() } }
  }
)

In the above example, my decision to use db.runCommand verses db.rooms.findAndModify was strategic. db.runCommand will return a status code as to whether the document was updated, which allows me to perform additional work if the return value was true. findAndModify simply returns the old document, unless the new flag is passed to the argument list by which it will return the updated document.

Related