-
Notifications
You must be signed in to change notification settings - Fork 20
DOCSP-41761 Add transaction page #104
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
stephmarie17
merged 9 commits into
mongodb:master
from
stephmarie17:docsp-41761-addTransactionPage
Sep 5, 2024
Merged
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
daee769
add transaction page and code example
stephmarie17 fcf50a0
fix typo
stephmarie17 4e9a2fd
update keywords
stephmarie17 ea860a8
update api docs links
stephmarie17 283331a
implement feedback
stephmarie17 7ce5b57
fix typo
stephmarie17 2e07a13
implement feedback
stephmarie17 540f74d
implement feedback
stephmarie17 af50e30
update wording
stephmarie17 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
# start-transaction | ||
# 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() | ||
# end-transaction |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 </sample-data>`. To learn how to create a | ||
free MongoDB Atlas cluster and load the sample datasets, see the | ||
:ref:`<pymongo-get-started>` 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 | ||
</reference/method/Session.startTransaction/>` 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 | ||
</reference/method/Session.abortTransaction/>` 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 | ||
</reference/method/Session.commitTransaction/>` 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 Type**: ``_T`` | ||
|
||
* - ``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 <api-docs-transaction>`. | ||
|
||
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 </core/transactions/>` | ||
- :manual:`Server Sessions </reference/server-sessions>` | ||
- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>` | ||
|
||
To learn more about ACID compliance, see the :website:`What are ACID | ||
Properties in Database Management Systems? </basics/acid-transactions>` | ||
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>`__ |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.