From 7809afbd948b64c27387785c81bdb18f8c2d1b39 Mon Sep 17 00:00:00 2001 From: Stephanie Aurelio Date: Thu, 5 Sep 2024 14:45:17 -0700 Subject: [PATCH] add new page and code example --- source/includes/write/transaction.kt | 54 ++++++++++ source/write-operations.txt | 1 + source/write/transactions.txt | 149 +++++++++++++++++++++++++++ 3 files changed, 204 insertions(+) create mode 100644 source/includes/write/transaction.kt create mode 100644 source/write/transactions.txt diff --git a/source/includes/write/transaction.kt b/source/includes/write/transaction.kt new file mode 100644 index 00000000..47b935c7 --- /dev/null +++ b/source/includes/write/transaction.kt @@ -0,0 +1,54 @@ +import com.mongodb.* +import com.mongodb.client.ClientSession +import com.mongodb.client.MongoClients +import com.mongodb.client.MongoCollection +import org.bson.Document + +fun main() { +// start-transaction + // Creates a new MongoClient with a connection string + val client = MongoClients.create("") + + // Gets the database and collection + val restaurantsDb = client.getDatabase("sample_restaurants") + val restaurantsCollection: MongoCollection = restaurantsDb.getCollection("restaurants") + + fun insertDocuments(session: ClientSession) { + // Sets options for the collection operation within the transaction + val restaurantsCollectionWithOptions = restaurantsCollection + .withWriteConcern(WriteConcern("majority")) + .withReadConcern(ReadConcern.LOCAL) + + // Inserts documents within the transaction + restaurantsCollectionWithOptions.insertOne( + session, + Document("name", "Kotlin Sync Pizza").append("cuisine", "Pizza") + ) + restaurantsCollectionWithOptions.insertOne( + session, + Document("name", "Kotlin Sync Burger").append("cuisine", "Burger") + ) + } + + // Starts a client session + client.startSession().use { session -> + try { + val txnOptions = TransactionOptions.builder() + .readConcern(ReadConcern.LOCAL) + .writeConcern(WriteConcern.MAJORITY) + .build() + + // Use the withTransaction method to start a transaction and execute the lambda function + session.withTransaction({ + insertDocuments(session) + println("Transaction succeeded") + }, txnOptions) + } catch (e: Exception) { + println("Transaction failed: ${e.message}") + } + } + + // Closes the MongoClient + client.close() +// end-transaction +} \ No newline at end of file diff --git a/source/write-operations.txt b/source/write-operations.txt index 7760534f..19b7e693 100644 --- a/source/write-operations.txt +++ b/source/write-operations.txt @@ -27,6 +27,7 @@ Write Data to MongoDB /write/replace /write/delete /write/bulk-write + /write/transactions .. /write/gridfs diff --git a/source/write/transactions.txt b/source/write/transactions.txt new file mode 100644 index 00000000..ed9d41f4 --- /dev/null +++ b/source/write/transactions.txt @@ -0,0 +1,149 @@ +.. _kotlin-sync-write-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+} driver to perform +**transactions**. 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 +session is a grouping of related read or write operations that you intend to run +sequentially. Sessions enable **causal consistency** for a +group of operations and allow you to run operations in an +**ACID-compliant transaction**, which is a transaction that meets an expectation +of atomicity, consistency, isolation, and durability. 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 ``MongoClient`` for multiple sessions and transactions instead of +creating 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`` collection +from the :atlas:`Atlas sample datasets `. To learn how to create a +free MongoDB Atlas cluster and load the sample datasets, see the +:ref:`` tutorial. + + +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 describes the methods you can use to +manage your transaction: + +.. list-table:: + :widths: 25 75 + :header-rows: 1 + + * - Method + - Description + + * - ``startTransaction()`` + - | Starts a new transaction, configured with the given options, on + this session. Returns an error if there is already + a transaction in progress for the session. To learn more about + this method, see the :manual:`startTransaction() page + ` in the Server manual. + | + | **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 has been committed or ended. To learn more about + this method, see the :manual:`abortTransaction() page + ` in the Server manual. + | + + * - ``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. To learn more about + this method, see the :manual:`commitTransaction() page + ` in the Server manual. + + * - ``withTransaction()`` + - | Starts a transaction on this session and runs the given function within + a transaction. + | + | **Parameters**: ``transactionBody, options`` + +Example +------- + +The following example demonstrates how to create a session, create a +transaction, and insert documents into multiple collections in one transaction +through the following steps: + +1. Create a session from the client by using the ``startSession()`` method. +#. Use the ``withTransaction()`` method to start a transaction. +#. Insert multiple documents. The ``withTransaction()`` method runs the + insert operation and commits the transaction. If any operation results in + errors, ``withTransaction()`` cancels the transaction. +#. Close the connection to the server by using the ``client.close()`` method. + +.. literalinclude:: /includes/write/transaction.kt + :start-after: start-transaction + :end-before: end-transaction + :language: kotlin + :copyable: + :dedent: + + +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-docs-transaction: + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the types or methods discussed in this +guide, see the following API documentation: + +- `ClientSession <{+api+}/com.mongodb.kotlin.client/-client-session/index.html>`_ +- `abortTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/abort-transaction.html>`_ +- `commitTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/commit-transaction.html>`_ +- `startTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/start-transaction.html>`_ +- `withTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/with-transaction.html>`_