Skip to content

Commit daee769

Browse files
committed
add transaction page and code example
1 parent 15d8174 commit daee769

File tree

3 files changed

+203
-0
lines changed

3 files changed

+203
-0
lines changed

source/includes/write/transaction.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# start-transaction
2+
# Establish a connection to the MongoDB server
3+
client = MongoClient("<connection string>")
4+
5+
# Define the database and collection
6+
restaurants_db = client["sample_restaurants"]
7+
restaurants_collection = restaurants_db["restaurants"]
8+
9+
# Function to perform the transaction
10+
def insert_documents(session):
11+
restaurants_collection_with_session = restaurants_collection.with_options(
12+
write_concern=WriteConcern("majority"),
13+
read_concern=ReadConcern("local")
14+
)
15+
16+
# Insert documents within the transaction
17+
restaurants_collection_with_session.insert_one(
18+
{"name": "PyMongo Pizza", "cuisine": "Pizza"}, session=session
19+
)
20+
restaurants_collection_with_session.insert_one(
21+
{"name": "PyMongo Burger", "cuisine": "Burger"}, session=session
22+
)
23+
24+
# Start a client session
25+
with client.start_session() as session:
26+
try:
27+
# Use the with_transaction method to start a transaction, execute the callback, and commit (or abort on error).
28+
session.with_transaction(insert_documents)
29+
print("Transaction succeeded")
30+
except (ConnectionFailure, OperationFailure) as e:
31+
print(f"Transaction failed: {e}")
32+
33+
# Close the client connection
34+
client.close()
35+
# end-transaction

source/write-operations.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ Write Data to MongoDB
2828
/write/delete
2929
/write/bulk-write
3030
/write/gridfs
31+
/write/transactions
3132

3233
Overview
3334
--------

source/write/transactions.txt

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
.. _pymongo-write-transactions:
2+
3+
============
4+
Transactions
5+
============
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: code example, rollback, undo operation
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+driver-long+} to perform
24+
**transactions**. :manual:`Transactions </core/transactions/>` allow
25+
you to run a series of operations that do not change any data until the
26+
transaction is committed. If any operation in the transaction returns an
27+
error, the driver cancels the transaction and discards all data changes
28+
before they ever become visible.
29+
30+
In MongoDB, transactions run within logical **sessions**. A
31+
:manual:`session </reference/server-sessions/>` is a grouping of related
32+
read or write operations that you intend to run sequentially. Sessions
33+
enable :manual:`causal consistency
34+
</core/read-isolation-consistency-recency/#causal-consistency>` for a
35+
group of operations or allow you to execute operations in an
36+
:website:`ACID transaction </basics/acid-transactions>`. MongoDB
37+
guarantees that the data involved in your transaction operations remains
38+
consistent, even if the operations encounter unexpected errors.
39+
40+
When using the {+driver-short+}, you can create a new session from a
41+
``MongoClient`` instance as a ``ClientSession`` type. We recommend that you reuse
42+
your ``MongoClient`` for multiple sessions and transactions instead of
43+
creating a new client each time.
44+
45+
.. warning::
46+
47+
Use a ``ClientSession`` only with the ``MongoClient`` (or associated
48+
``MongoDatabase`` or ``MongoCollection``) that created it. Using a
49+
``ClientSession`` with a different ``MongoClient`` results in operation
50+
errors.
51+
52+
Sample Data
53+
~~~~~~~~~~~
54+
55+
The examples in this guide use the ``sample_restaurants.restaurants`` collection
56+
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
57+
free MongoDB Atlas cluster and load the sample datasets, see the
58+
:ref:`<pymongo-get-started>` tutorial.
59+
60+
Methods
61+
-------
62+
63+
After you start a session by using the ``start_session()`` method, you can manage
64+
the session state by using the methods provided by the returned ``ClientSession``.
65+
66+
.. list-table::
67+
:widths: 25 75
68+
:header-rows: 1
69+
70+
* - Method
71+
- Description
72+
73+
* - ``start_transaction()``
74+
- | Starts a new transaction, configured with the given options, on
75+
this session. Returns an error if there is already
76+
a transaction in progress for the session. To learn more about
77+
this method, see the :manual:`startTransaction() page
78+
</reference/method/Session.startTransaction/>` in the Server manual.
79+
|
80+
| **Parameters**: ``read_concern``, ``write_concern``, ``read_preference``, ``max_commit_time_ms``
81+
| **Return Type**: ``ContextManager``
82+
83+
* - ``abort_transaction()``
84+
- | Ends the active transaction for this session. Returns an
85+
error if there is no active transaction for the session or the
86+
transaction has been committed or ended. To learn more about
87+
this method, see the :manual:`abortTransaction() page
88+
</reference/method/Session.abortTransaction/>` in the Server manual.
89+
|
90+
91+
* - ``commit_transaction()``
92+
- | Commits the active transaction for this session. Returns an
93+
error if there is no active transaction for the session or if the
94+
transaction was ended. To learn more about
95+
this method, see the :manual:`commitTransaction() page
96+
</reference/method/Session.commitTransaction/>` in the Server manual.
97+
98+
* - ``with_transaction()``
99+
- | Starts a transaction on this session and executes a callback once, then
100+
commits the transaction. In the event of an exception, this method may retry
101+
the commit or the entire transaction, which may invoke the callback multiple
102+
times by a single call to ``with_transaction``.
103+
|
104+
| **Parameters**: ``callback``, ``read_concern``, ``write_concern``, ``read_preference``, ``max_commit_time_ms``
105+
| **Return Type**: ``_T``
106+
107+
* - ``end_session()``
108+
- | Finishes this session. If a transaction has started, this method aborts it.
109+
Returns an error if there is no active session to end.
110+
111+
A ``ClientSession`` also has methods to retrieve session
112+
properties and modify mutable session properties. View the :ref:`API
113+
documentation <api-docs-transaction>` to learn more about these methods.
114+
115+
Example
116+
-------
117+
118+
The following example shows how you can create a session, create a
119+
transaction, and commit a multi-document insert operation through the
120+
following steps:
121+
122+
1. Create a session from the client using the ``start_session()`` method.
123+
#. Use the ``with_transaction()`` method to start a transaction.
124+
#. Insert multiple documents. The ``with_transaction()`` method executes the
125+
insert and commits the transaction. If any operation results in
126+
errors, ``with_transaction()`` handles canceling the transaction. This method
127+
ensures that the session closes properly when the block exits.
128+
#. Close the connection to the server with the ``client.close()`` method.
129+
130+
.. literalinclude:: /includes/write/transaction.py
131+
:start-after: start-transaction
132+
:end-before: end-transaction
133+
:language: python
134+
:copyable:
135+
:dedent:
136+
137+
If you require more control over your transactions, you can use the ``start_transaction()``
138+
method. You can use this method with the ``commit_transaction()`` and ``abort_transaction()``
139+
methods described in the preceding section to manually manage the transaction lifecycle.
140+
141+
Additional Information
142+
----------------------
143+
144+
To learn more about the concepts mentioned in this guide, see the following pages in
145+
the Server manual:
146+
147+
- :manual:`Transactions </core/transactions/>`
148+
- :manual:`Server Sessions </reference/server-sessions>`
149+
- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>`
150+
151+
To learn more about ACID compliance, see the :website:`What are ACID
152+
Properties in Database Management Systems? </basics/acid-transactions>`
153+
article on the MongoDB website.
154+
155+
.. _api-docs-transaction:
156+
157+
API Documentation
158+
~~~~~~~~~~~~~~~~~
159+
160+
To learn more about any of the types or methods discussed in this
161+
guide, see the following API Documentation:
162+
163+
- `ClietSession <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession>`__
164+
- `WriteConcern <{+api-root+}pymongo/write_concern.html#pymongo.write_concern.WriteConcern>`__
165+
- `start_transaction() <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession.start_transaction>`__
166+
- `with_transaction() <{+api-root+}pymongo/client_session.html#pymongo.client_session.ClientSession.with_transaction>`__
167+
- `insert_one() <{+api-root+}pymongo/collection.html#pymongo.collection.Collection.insert_one>`__

0 commit comments

Comments
 (0)