정의
Session.withTransaction( <function> [, <options> ] )mongosh v1.1.0의 새로운 기능
트랜잭션 내에서 지정된 Lambda 함수를 실행합니다. 오류가 발생하면 메서드는 다음을 다시 시도합니다.
커밋 작업(커밋 실패가 있는 경우)
전체 트랜잭션(오류가 허용되는 경우)
The
Session.withTransaction()method accepts the transaction options.반환합니다: 콜백 함수에 의해 생성된 값입니다.
중요
Mongo쉬 방법
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 드라이버 설명서를 참조하세요.
행동
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()으로 트랜잭션을 종료하고 커밋되지 않은 변경 사항을 롤백합니다.
참고
기본값 으로 MongoDB 초 이상 실행 트랜잭션을 60 종료합니다. 의 트랜잭션을 실험하기 위해 기본값 시간 제한을 mongosh 연장하려면 런타임 제한을 참조하세요.