定义
Session.withTransaction( <function> [, <options> ] )mongosh v1.1.0 中的新增内容
在事务中运行指定的 lambda 函数。如果出现错误,该方法将重试:
提交操作(如果提交失败)。
整个事务(如果此错误允许)。
Session.withTransaction()方法接受ACID 事务选项。返回: 回调函数生成的值。
重要
mongosh 方法
This page documents a
mongoshmethod. This is not the documentation for database commands or language-specific drivers, such as Node.js.有关数据库命令,请参阅
commitTransaction命令。如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。
兼容性
此方法可用于以下环境中托管的部署:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
注意
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
行为
The Node.js driver has a version of Session.withTransaction() that is known as the Callback API. The Callback API also accepts an callback, however the return type for the Node.js method must be a Promise. The mongosh Session.withTransaction() method does not require a Promise. Example -------
以下示例创建了 balances 集合,并使用事务在两个客户之间转账。
创建 balances 集合:
use accounts db.balances.insertMany( [ { customer: "Pat", balance: Decimal128( "35.88" ) }, { customer: "Sasha", balance: Decimal128( "5.23" ) } ] )
对事务中使用的某些变量进行初始化:
var fromAccount = "Pat" var toAccount = "Sasha" var transferAmount = 1 var dbName = "accounts" var collectionName = "balances"
启动会话,然后运行事务以更新账户:
var session = db.getMongo().startSession( { readPreference: { mode: "primary" } } ); session.withTransaction( async() => { const sessionCollection = session.getDatabase(dbName).getCollection(collectionName); // Check needed values var checkFromAccount = sessionCollection.findOne( { "customer": fromAccount, "balance": { $gte: transferAmount } } ) if( checkFromAccount === null ){ throw new Error( "Problem with sender account" ) } var checkToAccount = sessionCollection.findOne( { "customer": toAccount } ) if( checkToAccount === null ){ throw new Error( "Problem with receiver account" ) } // Transfer the funds sessionCollection.updateOne( { "customer": toAccount }, { $inc: { "balance": transferAmount } } ) sessionCollection.updateOne( { "customer": fromAccount }, { $inc: { "balance": -1 * transferAmount } } ) } )
Lambda 函数包括在更新balances集合之前验证操作的初始检查。
MongoDB 自动完成事务。
如果两个
updateOne()操作均成功,则Session.withTransaction()在回调返回时提交事务。如果回调内引发异常,
Session.withTransaction()将结束事务并回滚所有未提交的更改。
注意
By default, MongoDB ends transactions that run for more than 60 seconds. If you want to extend the default timeout to experiment with transactions in mongosh, see Runtime Limit.