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

Session.withTransaction()(mongosh方法)

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

mongosh v1.1.0 中的新增内容

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

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

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

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

返回:

回调函数生成的值。

重要

mongosh 方法

This page documents a mongosh method. 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.

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.

给本页内容打分

在此页面上