mongo事务

事务内的读取操作可能会返回旧数据,这称为 陈旧读取。事务内的读取操作不能保证看到其他已提交事务或非事务性写入执行的写入。

db.getSiblingDB("hr").employees.insertOne(
   { _id: 1, status: "Active" }
)
session = db.getMongo().startSession( { readPreference: { mode: "primary" } } )
session.startTransaction( { readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } } )

employeesCollection = session.getDatabase("hr").employees
employeeDoc = employeesCollection.findOneAndUpdate(
   { _id: 1, status: "Active" },
   { $set: { lockId: ObjectId() } },
   { returnNewDocument: true }
)

请注意,在事务内部,findOneAndUpdate操作会设置一个新lockId字段。您可以将lockId字段设置为任何值,只要它修改了文档即可。通过更新文档,事务将获得锁。

如果事务之外的操作在提交事务之前尝试修改文档,MongoDB 会向外部操作返回写冲突错误。

session.commitTransaction()

多文档事务支持"local"、、 "majority""snapshot"阅读关注级别。

对于分片集群上的事务,只有 "snapshot"读取关注才能提供跨多个分片的一致快照。

无论为事务指定了什么写关注,分片集群事务的提交操作都包含一些使用{w: "majority", j: true}写关注的部分。

 

 

 

 

 

 

 

 

posted @ 2024-07-18 20:18  wongchaofan  阅读(12)  评论(0编辑  收藏  举报