From 7ea0b7de0b971b40b62d890f1b2623a2515bfd95 Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Thu, 22 Aug 2024 14:14:10 -0700 Subject: [PATCH 01/12] add transaction page and code snippet --- source/fundamentals.txt | 1 + source/fundamentals/transactions.txt | 133 ++++++++++++++++++ .../code-snippets/Transaction.java | 37 +++++ 3 files changed, 171 insertions(+) create mode 100644 source/fundamentals/transactions.txt create mode 100644 source/includes/fundamentals/code-snippets/Transaction.java diff --git a/source/fundamentals.txt b/source/fundamentals.txt index 691fcda85..05d6e9b17 100644 --- a/source/fundamentals.txt +++ b/source/fundamentals.txt @@ -20,6 +20,7 @@ Fundamentals /fundamentals/aggregation /fundamentals/aggregation-expression-operations /fundamentals/indexes + /fundamentals/transactions /fundamentals/collations /fundamentals/logging /fundamentals/monitoring diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt new file mode 100644 index 000000000..28de63655 --- /dev/null +++ b/source/fundamentals/transactions.txt @@ -0,0 +1,133 @@ +============ +Transactions +============ + +.. default-domain:: mongodb + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to use the {+driver-short+} to perform +**transactions**. :manual:`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 ` is a grouping of related +read or write operations that you intend to run sequentially. Sessions +enable :manual:`causal consistency +` for a +group of operations or allow you to execute operations in an +:website:`ACID transaction `. 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 +``Client`` instance as a ``ClientSession``. We recommend that you reuse +your client for multiple sessions and transactions instead of +instantiating a new client each time. + +.. warning:: + + Use a ``Session`` only with the ``Client`` (or associated + ``Database`` or ``Collection``) that created it. Using a + ``Session`` with a different ``Client`` results in operation + errors. + +Methods +------- + +After you start a session by using the ``startSession()`` method, you can modify +the session state by using the method set provided by the ``Session`` interface. +The following table describes these methods: + +.. 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. + | + | **Parameter**: ``transactionBody`` + +A ``Session`` 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. + +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/Transactions.java + :language: java + +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 ` +- :manual:`Server Sessions ` +- :manual:`Read Isolation, Consistency, and Recency ` + +To learn more about ACID compliance, see the :website:`What are ACID +Properties in Database Management Systems? ` +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>`_ +- \ No newline at end of file diff --git a/source/includes/fundamentals/code-snippets/Transaction.java b/source/includes/fundamentals/code-snippets/Transaction.java new file mode 100644 index 000000000..afe055c69 --- /dev/null +++ b/source/includes/fundamentals/code-snippets/Transaction.java @@ -0,0 +1,37 @@ +import com.mongodb.*; +import com.mongodb.client.*; +import com.mongodb.client.model.WriteConcern; +import org.bson.Document; + +import java.util.Arrays; + +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 collection = database.getCollection("yourCollectionName"); + + // 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( + 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(); + } + } +} From 5ef670bdc4fff6ffa2d7027f46143f52d0b7272f Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Thu, 22 Aug 2024 14:48:27 -0700 Subject: [PATCH 02/12] update references --- source/fundamentals/transactions.txt | 5 +++-- source/includes/fundamentals/code-snippets/Transaction.java | 6 +++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt index 28de63655..af36fd3f9 100644 --- a/source/fundamentals/transactions.txt +++ b/source/fundamentals/transactions.txt @@ -97,8 +97,9 @@ and commit a multi-document insert operation through the following steps: the transaction. If any operation results in errors, ``withTransaction()`` handles canceling the transaction. -.. literalinclude:: /includes/fundamentals/code-snippets/Transactions.java +.. literalinclude:: /includes/fundamentals/code-snippets/Transaction.java :language: java + :start-after: end imports 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 @@ -130,4 +131,4 @@ guide, see the following API Documentation: - `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>`_ -- \ No newline at end of file + \ No newline at end of file diff --git a/source/includes/fundamentals/code-snippets/Transaction.java b/source/includes/fundamentals/code-snippets/Transaction.java index afe055c69..eb9d84916 100644 --- a/source/includes/fundamentals/code-snippets/Transaction.java +++ b/source/includes/fundamentals/code-snippets/Transaction.java @@ -1,9 +1,13 @@ -import com.mongodb.*; +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) { From f4055a8e172183c5400d0476d424b39ed10d49cb Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Fri, 23 Aug 2024 09:33:45 -0700 Subject: [PATCH 03/12] update metadata --- source/fundamentals/transactions.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt index af36fd3f9..175cbd700 100644 --- a/source/fundamentals/transactions.txt +++ b/source/fundamentals/transactions.txt @@ -1,3 +1,5 @@ +.. _java-fundamentals-transactions: + ============ Transactions ============ @@ -10,6 +12,13 @@ Transactions :depth: 2 :class: singlecol +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: ACID, write, consistency, code example + Overview -------- From fd6c16d2d3d0a36ee4c4ce0bea23ee6931c4ca69 Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Mon, 26 Aug 2024 12:47:50 -0700 Subject: [PATCH 04/12] update references --- source/fundamentals/transactions.txt | 20 +++++++++---------- .../code-snippets/Transaction.java | 3 ++- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt index 175cbd700..f5e0ad1c6 100644 --- a/source/fundamentals/transactions.txt +++ b/source/fundamentals/transactions.txt @@ -4,8 +4,6 @@ Transactions ============ -.. default-domain:: mongodb - .. contents:: On this page :local: :backlinks: none @@ -40,23 +38,24 @@ 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 -``Client`` instance as a ``ClientSession``. We recommend that you reuse +``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 ``Session`` only with the ``Client`` (or associated - ``Database`` or ``Collection``) that created it. Using a - ``Session`` with a different ``Client`` results in operation + 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 ------- -After you start a session by using the ``startSession()`` method, you can modify -the session state by using the method set provided by the ``Session`` interface. -The following table describes these 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 @@ -108,7 +107,8 @@ and commit a multi-document insert operation through the following steps: .. literalinclude:: /includes/fundamentals/code-snippets/Transaction.java :language: java - :start-after: end imports + :start-after: start transaction + :end-after: 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 diff --git a/source/includes/fundamentals/code-snippets/Transaction.java b/source/includes/fundamentals/code-snippets/Transaction.java index eb9d84916..29e670204 100644 --- a/source/includes/fundamentals/code-snippets/Transaction.java +++ b/source/includes/fundamentals/code-snippets/Transaction.java @@ -16,7 +16,7 @@ public static void main(String[] args) { try (MongoClient mongoClient = MongoClients.create(connectionString)) { MongoDatabase database = mongoClient.getDatabase("yourDatabaseName"); MongoCollection collection = database.getCollection("yourCollectionName"); - +// start transaction // Set transaction options TransactionOptions txnOptions = TransactionOptions.builder() .writeConcern(WriteConcern.MAJORITY) @@ -37,5 +37,6 @@ public static void main(String[] args) { } catch (Exception e) { e.printStackTrace(); } +// end transaction } } From c148d407ba3a1dfa853cf64f3232673cd0d25b71 Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Mon, 26 Aug 2024 12:52:37 -0700 Subject: [PATCH 05/12] update include --- source/fundamentals/transactions.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt index f5e0ad1c6..9471d3ea1 100644 --- a/source/fundamentals/transactions.txt +++ b/source/fundamentals/transactions.txt @@ -108,7 +108,7 @@ and commit a multi-document insert operation through the following steps: .. literalinclude:: /includes/fundamentals/code-snippets/Transaction.java :language: java :start-after: start transaction - :end-after: end 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 From a5b488a811a7f6fbd9263c216c0e6a92d4e666f6 Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Mon, 26 Aug 2024 13:05:28 -0700 Subject: [PATCH 06/12] update session reference --- source/fundamentals/transactions.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt index 9471d3ea1..f1260eeca 100644 --- a/source/fundamentals/transactions.txt +++ b/source/fundamentals/transactions.txt @@ -88,7 +88,7 @@ methods you can use to manage your transaction: | | **Parameter**: ``transactionBody`` -A ``Session`` also has methods to retrieve session properties and modify mutable +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. From 162eec34cb67c4c4b4cff0478e0c86890cc2cd76 Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Mon, 26 Aug 2024 14:45:08 -0700 Subject: [PATCH 07/12] review feedback --- source/fundamentals/transactions.txt | 29 ++++++++++--------- .../code-snippets/Transaction.java | 10 +++---- 2 files changed, 21 insertions(+), 18 deletions(-) diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt index f1260eeca..8343097b4 100644 --- a/source/fundamentals/transactions.txt +++ b/source/fundamentals/transactions.txt @@ -53,8 +53,8 @@ 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 +``MongoClient`` instance. You can then modify the session state by using the +methods provided by the ``ClientSession``. The following table describes the methods you can use to manage your transaction: .. list-table:: @@ -66,12 +66,12 @@ methods you can use to manage your transaction: * - ``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 + default transaction options. Pass an instance of ``TransactionOptions`` + as a parameter to start a transaction with given options. You cannot start a transaction if there's already an active transaction - on the session. + running in the session. | - | **Parameter**: ``transactionOptions`` + | **Parameter**: ``TransactionOptions transactionOptions`` * - ``abortTransaction()`` - | Ends the active transaction for this session. Returns an error @@ -84,13 +84,15 @@ methods you can use to manage your transaction: transaction was ended. * - ``withTransaction()`` - - | Starts a new transaction for this session and runs the given function. + - | Starts a new transaction for this session and runs the given function. This + method handles retries, committing, and aborting transactions. Pass an + instance of ``TransactionBody`` as a parameter that defines the + operations you want to execute within the transaction. | - | **Parameter**: ``transactionBody`` + | **Parameter**: ``TransactionBody 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. +session properties. View the :ref:`API Documentation` to learn more about these methods. Example ------- @@ -98,8 +100,8 @@ 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. +1. Create a session from the client by using the ``startSession()`` method. +#. Set transaction options to configure transaction 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 @@ -107,12 +109,13 @@ and commit a multi-document insert operation through the following steps: .. literalinclude:: /includes/fundamentals/code-snippets/Transaction.java :language: java + :dedent: :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. +manage the transaction lifecycle. See :ref:`Methods`. Additional Information ---------------------- diff --git a/source/includes/fundamentals/code-snippets/Transaction.java b/source/includes/fundamentals/code-snippets/Transaction.java index 29e670204..ec342a23f 100644 --- a/source/includes/fundamentals/code-snippets/Transaction.java +++ b/source/includes/fundamentals/code-snippets/Transaction.java @@ -12,11 +12,11 @@ public class Transaction { public static void main(String[] args) { // Connect to MongoDB - String connectionString = "mongodb://localhost:27017"; // Update with your MongoDB URI + String connectionString = ""; // Replace with your connection string try (MongoClient mongoClient = MongoClients.create(connectionString)) { - MongoDatabase database = mongoClient.getDatabase("yourDatabaseName"); - MongoCollection collection = database.getCollection("yourCollectionName"); -// start transaction + MongoDatabase database = mongoClient.getDatabase("transaction_db"); + MongoCollection collection = database.getCollection("books"); + // start transaction // Set transaction options TransactionOptions txnOptions = TransactionOptions.builder() .writeConcern(WriteConcern.MAJORITY) @@ -37,6 +37,6 @@ public static void main(String[] args) { } catch (Exception e) { e.printStackTrace(); } -// end transaction + // end transaction } } From 7f3f6c140868ebfc5f7c890b1a7771fa6a918781 Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Mon, 26 Aug 2024 15:14:08 -0700 Subject: [PATCH 08/12] add section links --- source/fundamentals/transactions.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt index 8343097b4..75b2efd76 100644 --- a/source/fundamentals/transactions.txt +++ b/source/fundamentals/transactions.txt @@ -92,7 +92,7 @@ methods you can use to manage your transaction: | **Parameter**: ``TransactionBody transactionBody`` A ``ClientSession`` also has methods to retrieve session properties and modify mutable -session properties. View the :ref:`API Documentation` to learn more about these methods. +session properties. View the `API Documentation`_ to learn more about these methods. Example ------- @@ -115,7 +115,7 @@ and commit a multi-document insert operation through the following steps: 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. See :ref:`Methods`. +manage the transaction lifecycle. See `Methods`_. Additional Information ---------------------- From 93641af3ae961d4641c0c3fc662c0710d9500724 Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Mon, 26 Aug 2024 15:36:21 -0700 Subject: [PATCH 09/12] update link and implement feedback --- source/fundamentals/transactions.txt | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt index 75b2efd76..2971e5470 100644 --- a/source/fundamentals/transactions.txt +++ b/source/fundamentals/transactions.txt @@ -92,7 +92,8 @@ methods you can use to manage your transaction: | **Parameter**: ``TransactionBody transactionBody`` A ``ClientSession`` also has methods to retrieve session properties and modify mutable -session properties. View the `API Documentation`_ to learn more about these methods. +session properties. View the :ref:`API +documentation ` to learn more about these methods. Example ------- @@ -114,8 +115,8 @@ and commit a multi-document insert operation through the following steps: :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. See `Methods`_. +method. You can use this method with the ``commitTransaction()`` and ``abortTransaction()`` +methods described in the preceding section to manually manage the transaction lifecycle. Additional Information ---------------------- @@ -131,6 +132,8 @@ To learn more about ACID compliance, see the :website:`What are ACID Properties in Database Management Systems? ` article on the MongoDB website. +.. _api-docs-transaction: + API Documentation ~~~~~~~~~~~~~~~~~ From 9fdbaa47702cf619a442904895d5f9aedbbf74cd Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Tue, 27 Aug 2024 08:33:55 -0700 Subject: [PATCH 10/12] update code comment spacing --- source/includes/fundamentals/code-snippets/Transaction.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/includes/fundamentals/code-snippets/Transaction.java b/source/includes/fundamentals/code-snippets/Transaction.java index ec342a23f..c41ebecab 100644 --- a/source/includes/fundamentals/code-snippets/Transaction.java +++ b/source/includes/fundamentals/code-snippets/Transaction.java @@ -16,7 +16,7 @@ public static void main(String[] args) { try (MongoClient mongoClient = MongoClients.create(connectionString)) { MongoDatabase database = mongoClient.getDatabase("transaction_db"); MongoCollection collection = database.getCollection("books"); - // start transaction + // start transaction // Set transaction options TransactionOptions txnOptions = TransactionOptions.builder() .writeConcern(WriteConcern.MAJORITY) From 4a5370433bf9602a130048bf95b2fdc0cbdd045c Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Tue, 27 Aug 2024 08:43:02 -0700 Subject: [PATCH 11/12] update code snippet include --- source/includes/fundamentals/code-snippets/Transaction.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/includes/fundamentals/code-snippets/Transaction.java b/source/includes/fundamentals/code-snippets/Transaction.java index c41ebecab..a79ad5bc0 100644 --- a/source/includes/fundamentals/code-snippets/Transaction.java +++ b/source/includes/fundamentals/code-snippets/Transaction.java @@ -11,12 +11,12 @@ public class Transaction { public static void main(String[] args) { - // Connect to MongoDB + // start transaction String connectionString = ""; // Replace with your connection string try (MongoClient mongoClient = MongoClients.create(connectionString)) { MongoDatabase database = mongoClient.getDatabase("transaction_db"); MongoCollection collection = database.getCollection("books"); - // start transaction + // Set transaction options TransactionOptions txnOptions = TransactionOptions.builder() .writeConcern(WriteConcern.MAJORITY) @@ -24,7 +24,7 @@ public static void main(String[] args) { try (ClientSession session = mongoClient.startSession()) { - // Use withTransaction and lambda for transactional operations + // Use withTransaction and lambda for transaction operations session.withTransaction(() -> { collection.insertMany(session, Arrays.asList( new Document("title", "The Bluest Eye").append("author", "Toni Morrison"), From de25e0cd156a95e445fa22f35af44514fd70135b Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Tue, 17 Sep 2024 08:24:17 -0700 Subject: [PATCH 12/12] add required param note --- source/fundamentals/transactions.txt | 5 +++++ source/includes/fundamentals/code-snippets/Transaction.java | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/source/fundamentals/transactions.txt b/source/fundamentals/transactions.txt index 2971e5470..352b6ad02 100644 --- a/source/fundamentals/transactions.txt +++ b/source/fundamentals/transactions.txt @@ -49,6 +49,11 @@ instantiating a new client each time. ``ClientSession`` with a different ``MongoClient`` results in operation errors. +.. important:: + + You must include the ``session`` as a parameter for any operations that you + want to include in a transaction. + Methods ------- diff --git a/source/includes/fundamentals/code-snippets/Transaction.java b/source/includes/fundamentals/code-snippets/Transaction.java index a79ad5bc0..1756b41dd 100644 --- a/source/includes/fundamentals/code-snippets/Transaction.java +++ b/source/includes/fundamentals/code-snippets/Transaction.java @@ -17,14 +17,14 @@ public static void main(String[] args) { MongoDatabase database = mongoClient.getDatabase("transaction_db"); MongoCollection collection = database.getCollection("books"); - // Set transaction options + // Sets transaction options TransactionOptions txnOptions = TransactionOptions.builder() .writeConcern(WriteConcern.MAJORITY) .build(); try (ClientSession session = mongoClient.startSession()) { - // Use withTransaction and lambda for transaction operations + // Uses withTransaction and lambda for transaction operations session.withTransaction(() -> { collection.insertMany(session, Arrays.asList( new Document("title", "The Bluest Eye").append("author", "Toni Morrison"),