Definition定义
Session.withTransaction( <function> [, <options> ] )New in mongosh v1.1.0mongoshv1.1.0中的新功能Runs a specified lambda function within a transaction. If there is an error, the method retries the:在事务中运行指定的lambda函数。如果出现错误,该方法将重试:commit operation, if there is a failure to commit.如果提交失败,则执行提交操作。entire transaction, if the error permits.如果错误允许,则执行整个事务。
TheSession.withTransaction()method accepts the transaction options.Session.withTransaction()方法接受事务选项。Returns:返回The value produced by the callback function.回调函数产生的值。Important
mongosh
Method方法This page documents a本页记录了一种mongoshmethod. This is not the documentation for database commands or language-specific drivers, such as Node.js.mongosh方法。这不是数据库命令或特定语言驱动程序(如Node.js)的文档。For the database command, see the有关数据库命令,请参阅commitTransactioncommand.commitTransaction命令。For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.有关MongoDB API驱动程序,请参阅特定语言的MongoDB驱动程序文档。
Compatibility兼容性
This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
Note
This command is supported in all MongoDB Atlas clusters. 所有MongoDB Atlas集群都支持此命令。For information on Atlas support for all commands, see Unsupported Commands.有关Atlas支持所有命令的信息,请参阅不支持的命令。
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Behavior行为
The Node.js driver has a version of Node.js驱动程序有一个版本的Session.withTransaction() that is known as the Callback API. Session.withTransaction(),称为回调API。The 回调API也接受回调,但是Node.js方法的返回类型必须是Promise。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 -------mongosh Session.withTransaction()方法不需要Promise。示例-------
The following example creates the 以下示例创建balances collection and uses a transaction to transfer money between two customers.balances(余额)集合,并使用事务在两个客户之间转账。
Create the 创建balances collection:balances(余额)集合:
use accounts
db.balances.insertMany( [
{ customer: "Pat", balance: Decimal128( "35.88" ) },
{ customer: "Sasha", balance: Decimal128( "5.23" ) }
] )
Initialize some variables that are used in the transaction:初始化事务中使用的一些变量:
var fromAccount = "Pat"
var toAccount = "Sasha"
var transferAmount = 1
var dbName = "accounts"
var collectionName = "balances"
Start a session, then run a transaction to update the accounts:启动会话,然后运行事务以更新帐户:
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 } }
)
} )
The lambda function includes initial checks to validate the operation before updating the lambda函数包括在更新balances collection.balances集合之前验证操作的初始检查。
MongoDB automatically completes the transaction.MongoDB自动完成事务。
If both如果两个updateOne()operations succeed,Session.withTransaction()commits the transaction when the callback returns.updateOne()操作都成功,Session.withTransaction()将在回调返回时提交事务。If an exception is thrown inside the callback,如果在回调中抛出异常,Session.withTransaction()ends the transaction and rolls back any uncommitted changes.Session.withTransaction()将结束事务并回滚任何未提交的更改。
Note
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 默认情况下,MongoDB会结束运行超过60秒的事务。如果您想延长默认超时时间以在mongosh, see Runtime Limit.mongosh中尝试事务,请参阅运行时限制。