Transactions
Overview
In this guide, you can learn how to use the PyMongo driver to perform transactions. Transactions allow you to run a series of operations that do not change any data until the transaction is committed. If any operation in the transaction returns an error, the driver cancels the transaction and discards all data changes before they ever become visible.
In MongoDB, transactions run within logical sessions. A session is a grouping of related read or write operations that you intend to run sequentially. Sessions enable causal consistency for a group of operations and allow you to run operations in an ACID-compliant transaction, which is a transaction that meets an expectation of atomicity, consistency, isolation, and durability. MongoDB guarantees that the data involved in your transaction operations remains consistent, even if the operations encounter unexpected errors.
When using PyMongo, you can create a new session from a
MongoClient
instance as a ClientSession
type. We recommend that you reuse
your MongoClient
for multiple sessions and transactions instead of
creating a new client each time.
Warning
Use a ClientSession
only with the MongoClient
(or associated
MongoDatabase
or MongoCollection
) that created it. Using a
ClientSession
with a different MongoClient
results in operation
errors.
Sample Data
The examples in this guide use the sample_restaurants.restaurants
collection
from the Atlas sample datasets. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the
Get Started with PyMongo tutorial.
Methods
After you start a session by using the start_session()
method, you can manage
the session state by using the following methods provided by the returned ClientSession
:
Method | Description |
---|---|
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. |
A ClientSession
also has methods to retrieve session
properties and modify mutable session properties. To learn more about these
methods, see the API documentation.
Example
The following example shows how you can create a session, create a transaction, and commit a multi-document insert operation through the following steps:
Create a session from the client by using the
start_session()
method.Use the
with_transaction()
method to start a transaction.Insert multiple documents. The
with_transaction()
method runs the insert operation and commits the transaction. If any operation results in errors,with_transaction()
cancels the transaction. This method ensures that the session closes properly when the block exits.Close the connection to the server by using the
client.close()
method.
# 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()
If you require more control over your transactions, you can use the start_transaction()
method. You can use this method with the commit_transaction()
and abort_transaction()
methods described in the preceding section to manually manage the transaction lifecycle.
Additional Information
To learn more about the concepts mentioned in this guide, see the following pages in the Server manual:
To learn more about ACID compliance, see the What are ACID Properties in Database Management Systems? article on the MongoDB website.
API Documentation
To learn more about any of the types or methods discussed in this guide, see the following API documentation: