AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

Session.withTransaction()(mongoshメソッド)

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

mongosh v1.1.0の新機能

トランザクション内で指定された Lambda 関数を実行します。エラーが発生した場合、メソッドは次の処理を再試行します。

  • コミット操作(コミットに失敗した場合)。

  • トランザクション全体(エラーが許容される場合)。

Session.withTransaction()メソッドは トランザクション オプションを受け入れます。

次の値を返します。

コールバック関数によって生成された値。

重要

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.

  • 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コレクションを作成し、トランザクションを使用して 2 人の顧客間での送金を処理します。

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.

このページを評価