For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Transactions

In this guide, you can learn how to use the Java Reactive Streams driver to perform transactions. Transactions allow you to run a series of operations that do not apply until all data changes are successful. If any operation in the transaction fails, the driver cancels the transaction and discards all data changes without ever becoming 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. With sessions, you can enable causal consistency for a group of operations, and run ACID transactions. MongoDB guarantees that the data involved in your transaction operations remains consistent, even if the operations encounter unexpected errors.

When using the Java Reactive Streams driver, 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.

The examples in this guide use the sample_restaurants.restaurants and sample_mflix.movies collections from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started.

Important

Project Reactor Library

This guide uses the Project Reactor library to consume Publisher instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see Getting Started in the Reactor documentation. To learn more about how we use Project Reactor library methods in this guide, see the Write Data to MongoDB guide.

MongoDB enables causal consistency in certain client sessions. The causal consistency model guarantees that in a distributed system, operations within a session run in a causal order. Clients observe results that are consistent with the causal relationships, or the dependencies between operations. For example, if you perform a series of operations where one operation logically depends on the result of another, any subsequent reads reflect the dependent relationship.

To guarantee causal consistency, client sessions must fulfill the following requirements:

  • When starting a session, the driver must enable the causal consistency option. This option is enabled by default.

  • Operations must run in a single session on a single thread. Otherwise, the sessions or threads must communicate the operation time and cluster time values to each other. To view an example of two sessions that communicate these values, see the Causal Consistency examples in the MongoDB Server manual.

  • You must use a MAJORITY read concern.

  • You must use a MAJORITY write concern. This is the default write concern value.

The following table describes the guarantees that causally consistent sessions provide:

Guarantee
Description

Read your writes

Read operations reflect the results of preceding write operations.

Monotonic reads

Read operations do not return results that reflect an earlier data state than a preceding read operation.

Monotonic writes

If a write operation must precede other write operations, the server runs this write operation first.

For example, if you call insertOne() to insert a document, then call updateOne() to modify the inserted document, the server runs the insert operation first.

Writes follow reads

If a write operation must follow other read operations, the server runs the read operations first.

For example, if you call find() to retrieve a document, then call deleteOne() to delete the retrieved document, the server runs the find operation first.

Tip

To learn more about the concepts mentioned in this section, see the following MongoDB Server manual entries:

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:

Method
Description

startTransaction()

Starts a new transaction, configured with the given options, on this session. Throws an exception if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the MongoDB Server manual.

abortTransaction()

Ends the active transaction for this session. Throws an exception if there is no active transaction for the session or if the transaction is already committed or ended. To learn more about this method, see the abortTransaction() page in the MongoDB Server manual.

commitTransaction()

Commits the active transaction for this session. Throws an exception if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the MongoDB Server manual.

Tip

Transaction Timeout

You can set a limit on amount of time that operations can take to complete in your transactions. To learn more, see the Transactions section of the Limit Server Execution Time guide.

The following example demonstrates how to create a session, create a transaction, and insert documents into multiple collections in one transaction. The code executes the following steps:

  1. Creates a session from the client by using the startSession() method

  2. Starts a transaction by using the startTransaction() method

  3. Inserts documents into the restaurants and movies collections

  4. Commits the transaction by using the commitTransaction() method

MongoClient mongoClient = MongoClients.create(settings);
MongoDatabase restaurantsDatabase = mongoClient.getDatabase("sample_restaurants");
MongoCollection<Document> restaurants = restaurantsDatabase.getCollection("restaurants");
MongoDatabase moviesDatabase = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> movies = moviesDatabase.getCollection("movies");
Mono.from(mongoClient.startSession())
.flatMap(session -> {
// Begins the transaction
session.startTransaction();
// Inserts documents in the given order
return Mono.from(restaurants.insertOne(session, new Document("name", "Reactive Streams Pizza").append("cuisine", "Pizza")))
.then(Mono.from(movies.insertOne(session, new Document("title", "Java: Into the Streams").append("type", "Movie"))))
// Commits the transaction
.flatMap(result -> Mono.from(session.commitTransaction())
.thenReturn(result))
.onErrorResume(error -> Mono.from(session.abortTransaction()).then(Mono.error(error)))
.doFinally(signalType -> session.close());
})
// Closes the client after the transaction completes
.doFinally(signalType -> mongoClient.close())
// Prints the results of the transaction
.subscribe(
result -> System.out.println("Transaction succeeded"),
error -> System.err.println("Transaction failed: " + error)
);

Note

Parallel Operations Not Supported

The Java Reactive Streams driver does not support running parallel operations within a single transaction.

If you're using MongoDB Server v8.0 or later, you can perform write operations on multiple namespaces within a single transaction by using bulk write operations. To learn more, see the Client Bulk Write section of the Bulk Write Operations guide.

To learn more about the concepts mentioned in this guide, see the following pages in the Server manual:

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