代碼實現以下:session
import pymongo mgClient = pymongo.MongoClient("ip", "port") session = mgClient.start_session() a_collection = mgClient.get_database("庫").集合名a b_collection = mgClient.get_database("庫").集合名b # 事務開始 session.start_transaction() try: a_collection.insert({"world":1}) b_collection.insert({"hello":1}) except: # 操做異常,中斷事務 session.abort_transaction() else: session.commit_transaction() finally: session.end_session()