-
Notifications
You must be signed in to change notification settings - Fork 17
DOCSP-39717 Transactions Page #74
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jordan-smith721
merged 7 commits into
mongodb:main
from
jordan-smith721:DOCSP-39717-transactions
Aug 29, 2024
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
cb0cf80
first draft transactions page
jordan-smith721 81b3eee
typos
jordan-smith721 17fe4b3
meta
jordan-smith721 2ddcb61
feedback
jordan-smith721 de0dcf4
fix list
jordan-smith721 0a41f08
trim code more
jordan-smith721 ba1dee2
fix code formatting
jordan-smith721 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
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) | ||
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
.. _java-rs-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**. 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 :manual:`causal consistency | ||
</core/read-isolation-consistency-recency/#causal-consistency>` for a | ||
group of operations, and run :website:`ACID transactions | ||
</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. | ||
|
||
Sample Data | ||
~~~~~~~~~~~ | ||
|
||
The examples in this guide use the ``sample_restaurants.restaurants`` and ``sample_mflix.movies`` collections | ||
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a | ||
free MongoDB Atlas cluster and load the sample datasets, see the | ||
:ref:`<java-rs-getting-started>`. | ||
|
||
.. include:: includes/reactor-note.rst | ||
|
||
Transaction 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: 40 60 | ||
:header-rows: 1 | ||
|
||
* - 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 :manual:`startTransaction() page | ||
</reference/method/Session.startTransaction/>` in the {+mdb-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 :manual:`abortTransaction() page | ||
</reference/method/Session.abortTransaction/>` in the {+mdb-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 :manual:`commitTransaction() page | ||
</reference/method/Session.commitTransaction/>` in the {+mdb-server+} manual. | ||
|
||
Transaction Example | ||
------------------- | ||
|
||
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 | ||
#. Starts a transaction by using the ``startTransaction()`` method | ||
#. Inserts documents into the ``restaurants`` and ``movies`` collections | ||
#. Commits the transaction by using the ``commitTransaction()`` method | ||
|
||
.. literalinclude:: /includes/write/transactions/transactions.java | ||
:language: java | ||
:copyable: | ||
:emphasize-lines: 26, 29, 33-36, 38 | ||
jordan-smith721 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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:`Causal Consistency </core/read-isolation-consistency-recency/#causal-consistency>` | ||
|
||
API Documentation | ||
~~~~~~~~~~~~~~~~~ | ||
|
||
To learn more about any of the types or methods discussed in this | ||
guide, see the following API Documentation: | ||
|
||
- `MongoClient <{+api+}/mongodb-driver-reactivestreams/com/mongodb/reactivestreams/client/MongoClient.html>`__ | ||
- `startSession() <{+api+}/mongodb-driver-reactivestreams/com/mongodb/reactivestreams/client/MongoClient.html#startSession()>`__ | ||
- `startTransaction() <{+api+}/mongodb-driver-reactivestreams/com/mongodb/reactivestreams/client/ClientSession.html#startTransaction()>`__ | ||
- `abortTransaction() <{+api+}/mongodb-driver-reactivestreams/com/mongodb/reactivestreams/client/ClientSession.html#abortTransaction()>`__ | ||
- `commitTransaction() <{+api+}/mongodb-driver-reactivestreams/com/mongodb/reactivestreams/client/ClientSession.html#commitTransaction()>`__ |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.