diff --git a/source/includes/write/transaction.py b/source/includes/write/transaction.py new file mode 100644 index 00000000..7a9a0600 --- /dev/null +++ b/source/includes/write/transaction.py @@ -0,0 +1,35 @@ +# start-transaction +# Establishes a connection to the MongoDB server +client = MongoClient("") + +# 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() +# end-transaction \ No newline at end of file diff --git a/source/write-operations.txt b/source/write-operations.txt index 0664b1eb..7ce72cb6 100644 --- a/source/write-operations.txt +++ b/source/write-operations.txt @@ -28,6 +28,7 @@ Write Data to MongoDB /write/delete /write/bulk-write /write/gridfs + /write/transactions Overview -------- diff --git a/source/write/transactions.txt b/source/write/transactions.txt new file mode 100644 index 00000000..749542df --- /dev/null +++ b/source/write/transactions.txt @@ -0,0 +1,168 @@ +.. _pymongo-write-transactions: + +============ +Transactions +============ + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: ACID, write, consistency, code example + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to use the {+driver-short+} 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 {+driver-short+}, 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:`Atlas sample datasets `. To learn how to create a +free MongoDB Atlas cluster and load the sample datasets, see the +:ref:`` 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``: + +.. list-table:: + :widths: 25 75 + :header-rows: 1 + + * - 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 :manual:`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 :manual:`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 :manual:`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 :ref:`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: + +1. 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. + +.. literalinclude:: /includes/write/transaction.py + :start-after: start-transaction + :end-before: end-transaction + :language: python + :copyable: + :dedent: + +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: + +- :manual:`Transactions ` +- :manual:`Server Sessions ` +- :manual:`Read Isolation, Consistency, and Recency ` + +To learn more about ACID compliance, see the :website:`What are ACID +Properties in Database Management Systems? ` +article on the MongoDB website. + +.. _api-docs-transaction: + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the types or methods discussed in this +guide, see the following API documentation: + +- `ClientSession <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession>`__ +- `WriteConcern <{+api-root+}pymongo/write_concern.html#pymongo.write_concern.WriteConcern>`__ +- `abort_transaction() <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession.abort_transaction>`__ +- `commit_transaction() <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession.commit_transaction>`__ +- `end_session() <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession.end_session>`__ +- `start_transaction() <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession.start_transaction>`__ +- `with_transaction() <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession.with_transaction>`__ +- `insert_one() <{+api-root+}pymongo/collection.html#pymongo.collection.Collection.insert_one>`__ \ No newline at end of file