Skip to content

Commit 7ea0b7d

Browse files
committed
add transaction page and code snippet
1 parent 5e844f5 commit 7ea0b7d

File tree

3 files changed

+171
-0
lines changed

3 files changed

+171
-0
lines changed

source/fundamentals.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ Fundamentals
2020
/fundamentals/aggregation
2121
/fundamentals/aggregation-expression-operations
2222
/fundamentals/indexes
23+
/fundamentals/transactions
2324
/fundamentals/collations
2425
/fundamentals/logging
2526
/fundamentals/monitoring

source/fundamentals/transactions.txt

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
============
2+
Transactions
3+
============
4+
5+
.. default-domain:: mongodb
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
Overview
14+
--------
15+
16+
In this guide, you can learn how to use the {+driver-short+} to perform
17+
**transactions**. :manual:`Transactions </core/transactions/>` allow
18+
you to run a series of operations that do not change any data until the
19+
transaction is committed. If any operation in the transaction returns an
20+
error, the driver cancels the transaction and discards all data changes
21+
before they ever become visible.
22+
23+
In MongoDB, transactions run within logical **sessions**. A
24+
:manual:`session </reference/server-sessions/>` is a grouping of related
25+
read or write operations that you intend to run sequentially. Sessions
26+
enable :manual:`causal consistency
27+
</core/read-isolation-consistency-recency/#causal-consistency>` for a
28+
group of operations or allow you to execute operations in an
29+
:website:`ACID transaction </basics/acid-transactions>`. MongoDB
30+
guarantees that the data involved in your transaction operations remains
31+
consistent, even if the operations encounter unexpected errors.
32+
33+
When using the {+driver-short+}, you can create a new session from a
34+
``Client`` instance as a ``ClientSession``. We recommend that you reuse
35+
your client for multiple sessions and transactions instead of
36+
instantiating a new client each time.
37+
38+
.. warning::
39+
40+
Use a ``Session`` only with the ``Client`` (or associated
41+
``Database`` or ``Collection``) that created it. Using a
42+
``Session`` with a different ``Client`` results in operation
43+
errors.
44+
45+
Methods
46+
-------
47+
48+
After you start a session by using the ``startSession()`` method, you can modify
49+
the session state by using the method set provided by the ``Session`` interface.
50+
The following table describes these methods:
51+
52+
.. list-table::
53+
:widths: 25 75
54+
:header-rows: 1
55+
56+
* - Method
57+
- Description
58+
59+
* - ``startTransaction()``
60+
- | Starts a new transaction for this session with the
61+
default transaction options. Use the ``TransactionOptions``
62+
parameter to start a transaction with given options. You
63+
cannot start a transaction if there's already an active transaction
64+
on the session.
65+
|
66+
| **Parameter**: ``transactionOptions``
67+
68+
* - ``abortTransaction()``
69+
- | Ends the active transaction for this session. Returns an error
70+
if there is no active transaction for the
71+
session or the transaction was previously ended.
72+
73+
* - ``commitTransaction()``
74+
- | Commits the active transaction for this session. Returns an
75+
error if there is no active transaction for the session or if the
76+
transaction was ended.
77+
78+
* - ``withTransaction()``
79+
- | Starts a new transaction for this session and runs the given function.
80+
|
81+
| **Parameter**: ``transactionBody``
82+
83+
A ``Session`` also has methods to retrieve session properties and modify mutable
84+
session properties. View the `API documentation <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html>`__
85+
to learn more about these methods.
86+
87+
Example
88+
-------
89+
90+
The following example demonstrates how you can create a session, create a transaction,
91+
and commit a multi-document insert operation through the following steps:
92+
93+
1. Create a session from the client using the ``startSession()`` method.
94+
#. Set transaction options to configure transactional behavior.
95+
#. Use the ``withTransaction()`` method to start a transaction.
96+
#. Insert multiple documents. The ``withTransaction()`` method executes, commits, and aborts
97+
the transaction. If any operation results in errors, ``withTransaction()`` handles canceling
98+
the transaction.
99+
100+
.. literalinclude:: /includes/fundamentals/code-snippets/Transactions.java
101+
:language: java
102+
103+
If you require more control over your transactions, you can use the ``startTransaction()``
104+
method. This method allows you to explicitly commit or abort the transaction and manually
105+
manage the transaction lifecycle.
106+
107+
Additional Information
108+
----------------------
109+
110+
To learn more about the concepts mentioned in this guide, see the following pages in
111+
the Server manual:
112+
113+
- :manual:`Transactions </core/transactions/>`
114+
- :manual:`Server Sessions </reference/server-sessions>`
115+
- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>`
116+
117+
To learn more about ACID compliance, see the :website:`What are ACID
118+
Properties in Database Management Systems? </basics/acid-transactions>`
119+
article on the MongoDB website.
120+
121+
API Documentation
122+
~~~~~~~~~~~~~~~~~
123+
124+
To learn more about any of the types or methods discussed in this
125+
guide, see the following API Documentation:
126+
127+
- `ClientSession <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html>`_
128+
- `startTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#startTransaction()>`_
129+
- `commitTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#commitTransaction()>`_
130+
- `abortTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#abortTransaction()>`_
131+
- `withTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#withTransaction(com.mongodb.client.TransactionBody)>`_
132+
- `TransactionOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/TransactionOptions.html>`_
133+
-
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import com.mongodb.*;
2+
import com.mongodb.client.*;
3+
import com.mongodb.client.model.WriteConcern;
4+
import org.bson.Document;
5+
6+
import java.util.Arrays;
7+
8+
public class Transaction {
9+
public static void main(String[] args) {
10+
// Connect to MongoDB
11+
String connectionString = "mongodb://localhost:27017"; // Update with your MongoDB URI
12+
try (MongoClient mongoClient = MongoClients.create(connectionString)) {
13+
MongoDatabase database = mongoClient.getDatabase("yourDatabaseName");
14+
MongoCollection<Document> collection = database.getCollection("yourCollectionName");
15+
16+
// Set transaction options
17+
TransactionOptions txnOptions = TransactionOptions.builder()
18+
.writeConcern(WriteConcern.MAJORITY)
19+
.build();
20+
21+
try (ClientSession session = mongoClient.startSession()) {
22+
23+
// Use withTransaction and lambda for transactional operations
24+
session.withTransaction(() -> {
25+
collection.insertMany(session, Arrays.asList(
26+
new Document("title", "The Bluest Eye").append("author", "Toni Morrison"),
27+
new Document("title", "Sula").append("author", "Toni Morrison"),
28+
new Document("title", "Song of Solomon").append("author", "Toni Morrison")
29+
));
30+
return null; // Return value as expected by the lambda
31+
}, txnOptions);
32+
}
33+
} catch (Exception e) {
34+
e.printStackTrace();
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)