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

柔情痞子 提交于 2021-01-27 04:52:07

问题


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 ?


回答1:


Yes, that's the classic use case for MongoDB's findAndModify command.

Specifically for pymongo: find_and_modify.




回答2:


All updates are atomic operations over a document. Now find_and_modify locks that document and returns it back in the same operation. This allows you to combine a lock over the document during find and then applies the update operation.

You can find more about atomic operations: http://www.mongodb.org/display/DOCS/Atomic+Operations

Best,

Norberto




回答3:


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.



来源:https://stackoverflow.com/questions/11991167/in-mongo-any-way-to-do-check-and-setting-like-atomic-operation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!