Docs Menu

트랜잭션

이 가이드 에서는 PyMongo 운전자 를 사용하여 트랜잭션 을 수행하는 방법을 학습 수 있습니다. 트랜잭션을 사용하면 트랜잭션 이 커밋될 때까지 데이터를 변경하지 않는 일련의 작업을 실행 수 있습니다. 트랜잭션 에서 오류가 반환되는 경우 운전자 는 트랜잭션 을 취소하고 데이터 변경 사항이 표시되기 전에 모든 데이터 변경 사항을 삭제합니다.

MongoDB 에서 트랜잭션은 논리적 세션 내에서 실행 . 세션은 순차적으로 실행 하려는 관련 읽기 또는 쓰기 (write) 작업의 그룹입니다. 세션을 사용하면 원자성, 일관성, 격리 및 내구성에 대한 기대치를 충족하는 트랜잭션 인 ACID 호환 트랜잭션에서 작업을 실행 수 있습니다. MongoDB 작업에 예기치 않은 오류가 발생하더라도 트랜잭션 작업과 관련된 데이터가 일관적인 유지하도록 보장 .

PyMongo 를 사용하는 경우 MongoClient 인스턴스 에서 ClientSession 유형으로 새 세션을 만들 수 있습니다. 매번 새 클라이언트 를 생성하는 대신 여러 세션 및 트랜잭션에 MongoClient 를 재사용하는 것이 좋습니다.

경고

ClientSession을(를) 생성한 MongoClient (또는 MongoDatabase 또는 MongoCollection)에만 {0}을(를) 사용합니다. 다른 MongoClient와(과) 함께 ClientSession을(를) 사용하면 작업 오류가 발생합니다.

MongoDB 클라이언트 세션에서 인과적 일관성 지원합니다. 인과적 일관성 모델은 세션 내의 작업이 인과적 순서로 실행 보장 . 클라이언트는 인과 관계 또는 작업 간의 종속성과 일관적인 결과를 관찰합니다. 예시 를 들어, 한 작업이 논리적으로 다른 작업의 결과에 따라 달라지는 일련의 작업을 수행하는 경우 모든 후속 읽기에는 종속 관계 반영됩니다.

참고

클라이언트 세션은 트랜잭션 수행하지 않더라도 인과적 일관성 유지합니다.

다음 표에서는 인과적으로 일관적인 세션이 제공하는 보장 에 대해 설명합니다.

보장
설명

쓰기 읽기

읽기 작업은 이전 쓰기 (write) 작업의 결과를 반영합니다.

단조적 읽기

읽기 작업은 이전 읽기 작업보다 이전 데이터 상태 반영하는 결과를 반환하지 않습니다.

단조로운 쓰기

쓰기 (write) 작업이 다른 쓰기 (write) 작업보다 선행되어야 하는 경우 운전자 이 쓰기 (write) 작업을 먼저 실행합니다.

예시 를 들어 insert_one() 를 호출하여 문서 삽입한 다음 update_one() 를 호출하여 삽입된 문서 수정하면 운전자 삽입 작업을 먼저 실행합니다.

읽기 후 쓰기

쓰기 (write) 작업이 다른 읽기 작업 뒤에 와야 하는 경우 운전자 읽기 작업을 먼저 실행합니다.

예시 를 들어 find() 를 호출하여 문서 조회 다음 delete_one() 를 호출하여 조회된 문서 삭제 하면 운전자 먼저 찾기 작업을 실행합니다.

인과적으로 일관적인 세션에서 MongoDB 다음 작업 간에만 인과적 일관성 보장 .

  • majority 읽기 고려 (read concern) 가 있는 읽기 작업

  • majority 쓰기 고려 (write concern) 가 있는 쓰기 작업

이 섹션에 언급된 개념에 대해 자세히 학습 다음 MongoDB Server 매뉴얼 항목을 참조하세요.

이 가이드 의 예제에서는 Atlas 샘플 데이터 세트sample_restaurants.restaurants 컬렉션 을 사용합니다. 무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 PyMongo 시작하기 튜토리얼을 참조하세요.

start_session() 메서드를 사용하여 세션을 시작한 후 반환된 ClientSession 에서 제공하는 다음 메서드를 사용하여 세션 상태 를 관리 할 수 있습니다.

메서드
설명

start_transaction()

Starts a new transaction, configured with the given options, on this session. Returns an error if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameters: read_concern, write_concern, read_preference, max_commit_time_ms
Return Type: ContextManager

abort_transaction()

Ends the active transaction for this session. Returns an error if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

commit_transaction()

Commits the active transaction for this session. Returns an error if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the Server manual.

with_transaction()

Starts a transaction on this session and runs callback once, then commits the transaction. In the event of an exception, this method may retry the commit or the entire transaction, which may invoke the callback multiple times by a single call to with_transaction().

Parameters: callback, read_concern, write_concern, read_preference, max_commit_time_ms
Return Value: The result of the callback function

end_session()

Finishes this session. If a transaction has started, this method aborts it. Returns an error if there is no active session to end.

ClientSession 에는 세션 속성을 조회 하고 변경 가능한 세션 속성을 수정하는 메서드도 있습니다. 이러한 메서드에 학습 보려면 API 설명서를 참조하세요.

다음 예시에서는 다음 단계를 통해 세션을 생성하고, 트랜잭션을 생성하고, 다중 문서 삽입 작업을 커밋하는 방법을 보여줍니다.

  1. start_session() 메서드를 사용하여 클라이언트에서 세션을 만듭니다.

  2. with_transaction() 메서드를 사용하여 트랜잭션을 시작합니다.

  3. 여러 문서를 삽입합니다. with_transaction() 메서드는 삽입 작업을 실행하고 트랜잭션 을 커밋합니다. 작업 중 오류가 발생하면 with_transaction() 트랜잭션 을 취소합니다. 이 메서드는 차단 이 종료될 때 세션이 제대로 닫히도록 합니다.

  4. client.close() 메서드를 사용하여 서버 와의 연결을 닫습니다.

# Establishes a connection to the MongoDB server
client = MongoClient("<connection string>")
# Defines the database and collection
restaurants_db = client["sample_restaurants"]
restaurants_collection = restaurants_db["restaurants"]
# Function performs the transaction
def insert_documents(session):
restaurants_collection_with_session = restaurants_collection.with_options(
write_concern=WriteConcern("majority"),
read_concern=ReadConcern("local")
)
# Inserts documents within the transaction
restaurants_collection_with_session.insert_one(
{"name": "PyMongo Pizza", "cuisine": "Pizza"}, session=session
)
restaurants_collection_with_session.insert_one(
{"name": "PyMongo Burger", "cuisine": "Burger"}, session=session
)
# Starts a client session
with client.start_session() as session:
try:
# Uses the with_transaction method to start a transaction, execute the callback, and commit (or abort on error).
session.with_transaction(insert_documents)
print("Transaction succeeded")
except (ConnectionFailure, OperationFailure) as e:
print(f"Transaction failed: {e}")
# Closes the client connection
client.close()

트랜잭션에 대한 더 많은 제어가 필요한 경우 start_transaction() 메서드를 사용할 수 있습니다. 이 메서드를 이전 섹션에서 설명한 commit_transaction()abort_transaction() 메서드와 함께 사용하여 트랜잭션 수명 주기를 수동으로 관리 있습니다.

참고

병렬 작업이 지원되지 않음

PyMongo 단일 트랜잭션 내에서 병렬 작업 실행 을 지원 하지 않습니다.

MongoDB Server v8.0 이상을 사용하는 경우 MongoClient 인스턴스 에서 bulk_write() 메서드를 호출하여 단일 트랜잭션 내에서 여러 네임스페이스에 대한 쓰기 (write) 작업을 수행할 수 있습니다. 자세한 내용은 대량 쓰기 작업 가이드 참조하세요.

이 가이드에 언급된 개념에 대해 자세히 알아보려면 서버 매뉴얼의 다음 페이지를 참조하세요.

ACID compliance 에 학습 보려면 데이터베이스 관리 시스템의 ACID 속성이란 무엇인가요?를 참조하세요. 문서를 MongoDB 웹사이트 에서 확인하세요.

이 가이드에서 설명하는 유형 또는 메서드에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.