Skip to content
Merged
1 change: 1 addition & 0 deletions source/fundamentals.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Fundamentals
/fundamentals/aggregation
/fundamentals/aggregation-expression-operations
/fundamentals/indexes
/fundamentals/transactions
/fundamentals/collations
/fundamentals/logging
/fundamentals/monitoring
Expand Down
143 changes: 143 additions & 0 deletions source/fundamentals/transactions.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
.. _java-fundamentals-transactions:

============
Transactions
============

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: ACID, write, consistency, code example

Overview
--------

In this guide, you can learn how to use the {+driver-short+} to perform
**transactions**. :manual:`Transactions </core/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
:manual:`session </reference/server-sessions/>` is a grouping of related
read or write operations that you intend to run sequentially. Sessions
enable :manual:`causal consistency
</core/read-isolation-consistency-recency/#causal-consistency>` for a
group of operations or allow you to execute operations in an
:website:`ACID transaction </basics/acid-transactions>`. MongoDB
guarantees that the data involved in your transaction operations remains
consistent, even if the operations encounter unexpected errors.

When using the {+driver-short+}, you can create a new session from a
``MongoClient`` instance as a ``ClientSession`` type. We recommend that you reuse
your client for multiple sessions and transactions instead of
instantiating 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.

Methods
-------

Create a ``ClientSession`` by using the ``startSession()`` method on your
``MongoClient``instance. You can then modify the session state by using the
methods provided by the ``ClientSession``. The following table details the
methods you can use to manage your transaction:

.. list-table::
:widths: 25 75
:header-rows: 1

* - Method
- Description

* - ``startTransaction()``
- | Starts a new transaction for this session with the
default transaction options. Use the ``TransactionOptions``
parameter to start a transaction with given options. You
cannot start a transaction if there's already an active transaction
on the session.
|
| **Parameter**: ``transactionOptions``

* - ``abortTransaction()``
- | Ends the active transaction for this session. Returns an error
if there is no active transaction for the
session or the transaction was previously ended.

* - ``commitTransaction()``
- | 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.

* - ``withTransaction()``
- | Starts a new transaction for this session and runs the given function.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: add to this description some info about defining a transactionBody

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: in this description, you can also mention that this method comprises the "Convenient Transaction API" because it starts commits and handles errors all in the same method.

|
| **Parameter**: ``transactionBody``

A ``ClientSession`` also has methods to retrieve session properties and modify mutable
session properties. View the `API documentation <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html>`__
to learn more about these methods.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: instead of linking to clientsession api docs, just reroute to the api docs section at the bottom of this guide

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QQ what's the syntax for this in rst? I didn't see this in the slide deck and what I found in other references didn't seem to work. Still getting used to using this instead of markdown!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Think I figured it out actually!

Example
-------

The following example demonstrates 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 using the ``startSession()`` method.
#. Set transaction options to configure transactional behavior.
#. Use the ``withTransaction()`` method to start a transaction.
#. Insert multiple documents. The ``withTransaction()`` method executes, commits, and aborts
the transaction. If any operation results in errors, ``withTransaction()`` handles canceling
the transaction.

.. literalinclude:: /includes/fundamentals/code-snippets/Transaction.java
:language: java
:start-after: start transaction
:end-before: end transaction

If you require more control over your transactions, you can use the ``startTransaction()``
method. This method allows you to explicitly commit or abort the transaction and 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 Documentation
~~~~~~~~~~~~~~~~~

To learn more about any of the types or methods discussed in this
guide, see the following API Documentation:

- `ClientSession <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html>`_
- `startTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#startTransaction()>`_
- `commitTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#commitTransaction()>`_
- `abortTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#abortTransaction()>`_
- `withTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#withTransaction(com.mongodb.client.TransactionBody)>`_
- `TransactionOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/TransactionOptions.html>`_

42 changes: 42 additions & 0 deletions source/includes/fundamentals/code-snippets/Transaction.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package fundamentals;

// begin imports
import com.mongodb.client.*;
import com.mongodb.client.MongoClient;
import com.mongodb.client.model.WriteConcern;
import org.bson.Document;

import java.util.Arrays;
// end imports

public class Transaction {
public static void main(String[] args) {
// Connect to MongoDB
String connectionString = "mongodb://localhost:27017"; // Update with your MongoDB URI
try (MongoClient mongoClient = MongoClients.create(connectionString)) {
MongoDatabase database = mongoClient.getDatabase("yourDatabaseName");
MongoCollection<Document> collection = database.getCollection("yourCollectionName");
// start transaction
// Set transaction options
TransactionOptions txnOptions = TransactionOptions.builder()
.writeConcern(WriteConcern.MAJORITY)
.build();

try (ClientSession session = mongoClient.startSession()) {

// Use withTransaction and lambda for transactional operations
session.withTransaction(() -> {
collection.insertMany(session, Arrays.asList(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add a note / important block in the documentation reminding users that they must include the session as a parameter for the operation to be part of the transaction.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this callout. Adding an admonition to the Overview section.

new Document("title", "The Bluest Eye").append("author", "Toni Morrison"),
new Document("title", "Sula").append("author", "Toni Morrison"),
new Document("title", "Song of Solomon").append("author", "Toni Morrison")
));
return null; // Return value as expected by the lambda
}, txnOptions);
}
} catch (Exception e) {
e.printStackTrace();
}
// end transaction
}
}
Loading