ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

Transactions

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 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.

MongoDB enables causal consistency in client sessions. The causal consistency model guarantees that operations within a session run in a causal order. Clients observe results that are consistent with the causal relationships, or the dependencies between operations. For example, if you perform a series of operations where one operation logically depends on the result of another, any subsequent reads reflect the dependent relationship.

The following table describes the guarantees that causally consistent sessions provide:

Guarantee
Description

Read your writes

Read operations reflect the results of preceding write operations.

Monotonic reads

Read operations do not return results that reflect an earlier data state than a preceding read operation.

Monotonic writes

If a write operation must precede other write operations, the driver runs this write operation first.

For example, if you call insert_one() to insert a document, then call update_one() to modify the inserted document, the driver runs the insert operation first.

Writes follow reads

If a write operation must follow other read operations, the driver runs the read operations first.

For example, if you call find() to retrieve a document, then call delete_one() to delete the retrieved document, the driver runs the find operation first.

In a causally consistent session, MongoDB ensures a causal relationship between the following operations:

  • Read operations that have a majority read concern

  • Write operations that have a majority write concern

Tip

To learn more about the concepts mentioned in this section, see the following MongoDB Server manual entries:

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.

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.

The following example shows how you can create a session, create a transaction, and commit a multi-document insert operation through the following steps:

  1. Create a session from the client by using the start_session() method.

  2. Use the with_transaction() method to start a transaction.

  3. 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.

  4. 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.

Note

Parallel Operations Not Supported

PyMongo does not support running parallel operations within a single transaction.

If you're using MongoDB Server v8.0 or later, you can perform write operations on multiple namespaces within a single transaction by calling the bulk_write() method on a MongoClient instance. For more information, see the Bulk Write Operations guide.

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.

To learn more about any of the types or methods discussed in this guide, see the following API documentation: