Skip to content

Commit c1d34d1

Browse files
authored
DOCSP-41761 Add transaction page (#104)
Add transactions page and code example
1 parent a99aef0 commit c1d34d1

File tree

3 files changed

+204
-0
lines changed

3 files changed

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

0 commit comments

Comments
 (0)