定义
commitTransaction将操作所做的更改保存在多文档事务中并结束该事务。
提示
In
mongosh, this command can also be run through theSession.commitTransaction()andSession.withTransaction()helper methods.Helper methods are convenient for
mongoshusers, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.To run the
commitTransaction, the command must be run against theadmindatabase and run within aSession().
兼容性
此命令可用于以下环境中托管的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
注意
所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
该命令具有以下语法:
db.adminCommand( { commitTransaction: 1, txnNumber: <long>, writeConcern: <document>, autocommit: false, comment: <any> } )
行为
写关注
提交事务时,会话使用事务开始时指定的写关注。请参阅 Session.startTransaction()。
如果您使用 "w: 1" 写关注进行提交,则可以在存在故障转移时回滚事务。
原子性(Atomicity)
在事务提交时,事务中所做的所有数据更改都会保存,并且在事务之外可见。换言之,一个事务不会在回滚其他事务的同时提交某些更改。
在事务进行提交前,在事务中所做的数据更改在事务外不可见。
不过,当事务写入多个分片时,并非所有外部读取操作都需等待已提交事务的结果在各个分片上可见。例如,如果事务已提交并且写入 1 在分片 A 上可见,但写入 2 在分片 B 上尚不可见,则读关注 "local" 处的外部读取可以在不看到写入 2 的情况下读取写入 1 的结果。