事务锁定 MongoDB

Transaction lock in MongoDB

我正在尝试开发一个预订系统,在检查其可用性后预订不同的资产。系统首先尝试从数据库中读取记录并检查被预订的槽位是否可用。如果是这样,系统会通过向系统中插入一条新记录来为他们预订空位。

现在的问题是,如果有多个用户请求预订,并且由于对数据库的多个请求可以交错,所以可能会出现这种情况。

User 1 -> read request start
User 2 -> read request start
User 1 -> read request success (booking available)
User 2 -> read request success (booking available)
User 1 -> write a new record to the db (new booking)
User 2 -> write a new record to the db (new booking) but this conflicts with User 1.

为了避免这种情况,理想情况下,我什至在读取操作开始之前就必须获得集合级别的锁,并且只有在最终写入完成后才释放锁。

我的理解对吗?如果可以,可以在 MongoDB 中完成吗?

非常欢迎使用 MongoDB、Mongoose 或 @tsed/mongoose 的任何解决方案。

MongoDB 4.0 之前的版本不支持事务。要在 4.0 中使用事务,请查看 https://www.mongodb.com/transactions

4.0以上版本可以使用findOneAndUpdate方法来模拟

例如,您可以这样进行修改查询:

record = db.collection.findOneAndUpdate({"in_transaction": {"$exists": False}}, {"$set": {"in_transaction": true}})

现在即使您 运行 两个同时查询也只有一个 return 文档。