|
| 1 | +.. _kotlin-sync-write-transactions: |
| 2 | + |
| 3 | +============ |
| 4 | +Transactions |
| 5 | +============ |
| 6 | + |
| 7 | +.. contents:: On this page |
| 8 | + :local: |
| 9 | + :backlinks: none |
| 10 | + :depth: 2 |
| 11 | + :class: singlecol |
| 12 | + |
| 13 | +.. facet:: |
| 14 | + :name: genre |
| 15 | + :values: reference |
| 16 | + |
| 17 | +.. meta:: |
| 18 | + :keywords: ACID, write, consistency, code example |
| 19 | + |
| 20 | +Overview |
| 21 | +-------- |
| 22 | + |
| 23 | +In this guide, you can learn how to use the {+driver-short+} to perform |
| 24 | +**transactions**. Transactions allow you to run a series of operations that do |
| 25 | +not change any data until the transaction is committed. If any operation in |
| 26 | +the transaction returns an error, the driver cancels the transaction and discards |
| 27 | +all data changes before they ever become visible. |
| 28 | + |
| 29 | +In MongoDB, transactions run within logical **sessions**. A |
| 30 | +session is a grouping of related read or write operations that you intend to run |
| 31 | +sequentially. Sessions enable **causal consistency** for a |
| 32 | +group of operations and allow you to run operations in an |
| 33 | +**ACID-compliant transaction**, which is a transaction that meets an expectation |
| 34 | +of atomicity, consistency, isolation, and durability. MongoDB guarantees that the |
| 35 | +data involved in your transaction operations remains consistent, even if the |
| 36 | +operations encounter unexpected errors. |
| 37 | + |
| 38 | +When using the {+driver-short+}, you can create a new session from a |
| 39 | +``MongoClient`` instance as a ``ClientSession`` type. We recommend that you reuse |
| 40 | +your ``MongoClient`` for multiple sessions and transactions instead of |
| 41 | +creating a new client each time. |
| 42 | + |
| 43 | +.. warning:: |
| 44 | + |
| 45 | + Use a ``ClientSession`` only with the ``MongoClient`` (or associated |
| 46 | + ``MongoDatabase`` or ``MongoCollection``) that created it. Using a |
| 47 | + ``ClientSession`` with a different ``MongoClient`` results in operation |
| 48 | + errors. |
| 49 | + |
| 50 | +Sample Data |
| 51 | +~~~~~~~~~~~ |
| 52 | + |
| 53 | +The examples in this guide use the ``sample_restaurants.restaurants`` collection |
| 54 | +from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a |
| 55 | +free MongoDB Atlas cluster and load the sample datasets, see the |
| 56 | +:atlas:`Get Started with Atlas </getting-started>` guide. |
| 57 | + |
| 58 | +The documents in this collection are modeled by the following {+language+} data class: |
| 59 | + |
| 60 | +.. literalinclude:: /includes/write/transaction.kt |
| 61 | + :start-after: start-data-class |
| 62 | + :end-before: end-data-class |
| 63 | + :language: kotlin |
| 64 | + :copyable: |
| 65 | + :dedent: |
| 66 | + |
| 67 | +Methods |
| 68 | +------- |
| 69 | + |
| 70 | +Create a ``ClientSession`` by using the ``startSession()`` method on your ``MongoClient`` |
| 71 | +instance. You can then modify the session state by using the methods provided by |
| 72 | +the ``ClientSession``. The following table describes the methods you can use to |
| 73 | +manage your transaction: |
| 74 | + |
| 75 | +.. list-table:: |
| 76 | + :widths: 25 75 |
| 77 | + :header-rows: 1 |
| 78 | + |
| 79 | + * - Method |
| 80 | + - Description |
| 81 | + |
| 82 | + * - ``startTransaction()`` |
| 83 | + - | Starts a new transaction, configured with the given options, on |
| 84 | + this session. Returns an error if there is already |
| 85 | + a transaction in progress for the session. To learn more about |
| 86 | + this method, see the :manual:`startTransaction() page |
| 87 | + </reference/method/Session.startTransaction/>` in the Server manual. |
| 88 | + | |
| 89 | + | **Parameter**: ``TransactionOptions`` |
| 90 | + |
| 91 | + * - ``abortTransaction()`` |
| 92 | + - | Ends the active transaction for this session. Returns an |
| 93 | + error if there is no active transaction for the session or the |
| 94 | + transaction has been committed or ended. To learn more about |
| 95 | + this method, see the :manual:`abortTransaction() page |
| 96 | + </reference/method/Session.abortTransaction/>` in the Server manual. |
| 97 | + | |
| 98 | + |
| 99 | + * - ``commitTransaction()`` |
| 100 | + - | Commits the active transaction for this session. Returns an |
| 101 | + error if there is no active transaction for the session or if the |
| 102 | + transaction was ended. To learn more about |
| 103 | + this method, see the :manual:`commitTransaction() page |
| 104 | + </reference/method/Session.commitTransaction/>` in the Server manual. |
| 105 | + |
| 106 | + * - ``withTransaction()`` |
| 107 | + - | Starts a transaction on this session and runs the given function within |
| 108 | + a transaction. |
| 109 | + | |
| 110 | + | **Parameters**: transaction body function, ``TransactionOptions`` |
| 111 | + |
| 112 | +Example |
| 113 | +------- |
| 114 | + |
| 115 | +The following example demonstrates how to create a session, create a |
| 116 | +transaction, and insert documents into a collection in one transaction |
| 117 | +through the following steps: |
| 118 | + |
| 119 | +1. Create a session from the client by using the ``startSession()`` method. |
| 120 | +#. Define the ``insertRestaurantsInTransaction()`` method to insert multiple |
| 121 | + documents into the ``restaurants`` collection. |
| 122 | +#. Use the ``withTransaction()`` method to start a transaction. The ``withTransaction()`` |
| 123 | + method runs the insert operations and commits the transaction. If any |
| 124 | + operation results in errors, ``withTransaction()`` cancels the transaction. |
| 125 | +#. Close the connection to the server by using the ``MongoClient.close()`` method. |
| 126 | + |
| 127 | +.. literalinclude:: /includes/write/transaction.kt |
| 128 | + :start-after: start-transaction |
| 129 | + :end-before: end-transaction |
| 130 | + :language: kotlin |
| 131 | + :copyable: |
| 132 | + :dedent: |
| 133 | + |
| 134 | +If you require more control over your transactions, you can use the ``startTransaction()`` |
| 135 | +method. You can use this method with the ``commitTransaction()`` and ``abortTransaction()`` |
| 136 | +methods described in the preceding section to manually manage the transaction lifecycle. |
| 137 | + |
| 138 | +Additional Information |
| 139 | +---------------------- |
| 140 | + |
| 141 | +To learn more about the concepts mentioned in this guide, see the following pages in |
| 142 | +the Server manual: |
| 143 | + |
| 144 | +- :manual:`Transactions </core/transactions/>` |
| 145 | +- :manual:`Server Sessions </reference/server-sessions>` |
| 146 | +- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>` |
| 147 | + |
| 148 | +To learn more about ACID compliance, see the :website:`What are ACID |
| 149 | +Properties in Database Management Systems? </basics/acid-transactions>` |
| 150 | +article on the MongoDB website. |
| 151 | + |
| 152 | +.. _kotlin-sync-api-docs-transaction: |
| 153 | + |
| 154 | +API Documentation |
| 155 | +~~~~~~~~~~~~~~~~~ |
| 156 | + |
| 157 | +To learn more about any of the types or methods discussed in this |
| 158 | +guide, see the following API documentation: |
| 159 | + |
| 160 | +- `ClientSession <{+api+}/com.mongodb.kotlin.client/-client-session/index.html>`_ |
| 161 | +- `abortTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/abort-transaction.html>`_ |
| 162 | +- `commitTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/commit-transaction.html>`_ |
| 163 | +- `startTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/start-transaction.html>`_ |
| 164 | +- `withTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/with-transaction.html>`_ |
0 commit comments