对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

Session.withTransaction()(mongosh方法)

Session.withTransaction( <function> [, <options> ] )

mongosh v1.1.0 中的新增内容

在事务中运行指定的 lambda 函数。如果出现错误,该方法将重试:

  • 提交操作(如果提交失败)。

  • 整个事务(如果此错误允许)。

Session.withTransaction() 方法接受ACID 事务选项。

返回:

回调函数生成的值。

重要

mongosh 方法

本页面提供 mongosh 方法的相关信息。这不是数据库命令或特定语言驱动程序(例如 Node.js)的相关文档。

有关数据库命令,请参阅 commitTransaction 命令。

如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。

Node.js 驱动程序的 Session.withTransaction() 版本被称为 Callback API。Callback API 还接受回调,但 Node.js 方法的返回类型必须是 Promise。mongosh Session.withTransaction() 方法不需要 Promise。示例 -------

以下示例创建了 balances 集合,并使用事务在两个客户之间转账。

创建 balances 集合:

use accountsdb.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() 将结束事务并回滚所有未提交的更改。

注意

默认情况下,MongoDB 会结束运行超过 60 秒的事务。如果您想延长默认超时时间,以试验 mongosh 中的事务,请参阅运行时限制。

给本页内容打分

在此页面上