MongoDB 4.0 多文档事务相关

在MongoDB4.0版本之前只支持单文档事务操作,在4.0版本之后开始支持多文档事务操作

image

事务和副本集

在MongoDB中多文档事务操作只支持副本集的操作,关于在分片上的事务操作会在4.2版本中引入

存储引擎

在MongoDB中只有 WiredTiger 存储引擎才支持多文档事务操作,在 in-memoryMMAPv1存储引擎
中不支持多文档事务操作

事务和操作

  • 事务支持在已经存在的collections中进行 CURD 操作,collections可以在不同的数据库中
  • configadmin collections和local数据库中不支持读写事务
  • system.* collections中也不支持事务
  • 事务支持计划查询 如 explain
  • 在事务之外创建的 cursors ,在事务中不能进行 getMore 操作
  • 在事务中创建的 cursors,在事务外也不能进行 getMore 操作

支持多文档事务的操作

方法 命令 备注
db.collection.aggregate() aggregate 不包含:
collStats](https://docs.mongodb.com/manual/reference/operator/aggregation/collStats/#pipe._S_collStats)
[
currentOp

indexStats](https://docs.mongodb.com/manual/reference/operator/aggregation/indexStats/#pipe._S_indexStats) [listLocalSessions
listSessions](https://docs.mongodb.com/manual/reference/operator/aggregation/listSessions/#pipe._S_listSessions)
[
out
db.collection.distinct() distinct
db.collection.find() find
geoSearch
db.collection.deleteMany()
db.collection.deleteOne()
db.collection.remove()
delete
db.collection.findOneAndDelete()
db.collection.findOneAndReplace()
db.collection.findOneAndUpdate()
findAndModify 对于upsert,只对已经存在的 collection有效
db.collection.insertMany()
db.collection.insertOne()
db.collection.insert()
insert 对 已经存在的collection有效
db.collection.save() 如果是 insert 操作,只有 collection 存在时才有效
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
db.collection.update()
update upsert, 只对已经存在的 collection有效
db.collection.bulkWrite() 对于upsert,只对已经存在的 collection有效
如果是 insert 操作,只有 collection 存在时才有效

Count操作

为了在事务中使用count操作,请在 aggregation stage中使用 count](https://docs.mongodb.com/manual/reference/operator/aggregation/count/#pipe._S_count)或者在 `aggregation stage`中使用 [group使用 $sum操作

信息的操作

查询信息相关的操作 isMaster, buildInfo,connectionStatus和其他相关的辅助方法,都可以在事务中操作,但是这些方法不能作为事务中的第一个操作

限制的操作

下面的操作不能再多文档事务中操作

事务和 mongo Shell

mongo Shell中的相关的事务方法

原子性

MongoDB中的多文档事务也是原子性的

事务和锁

默认情况下,事务等待5毫秒以获取事务中操作所需的锁。如果事务不能在5毫秒内获取其所需的锁,则事务中止。
可以使用 maxTransactionLockRequestTimeoutMillis
调整这个时间

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容