|
| 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+} driver 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 | +:ref:`<pymongo-get-started>` tutorial. |
| 57 | + |
| 58 | + |
| 59 | +Create a ``ClientSession`` by using the ``startSession()`` method on your ``MongoClient`` |
| 60 | +instance. You can then modify the session state by using the methods provided by |
| 61 | +the ``ClientSession``. The following table describes the methods you can use to |
| 62 | +manage your transaction: |
| 63 | + |
| 64 | +.. list-table:: |
| 65 | + :widths: 25 75 |
| 66 | + :header-rows: 1 |
| 67 | + |
| 68 | + * - Method |
| 69 | + - Description |
| 70 | + |
| 71 | + * - ``startTransaction()`` |
| 72 | + - | Starts a new transaction, configured with the given options, on |
| 73 | + this session. Returns an error if there is already |
| 74 | + a transaction in progress for the session. To learn more about |
| 75 | + this method, see the :manual:`startTransaction() page |
| 76 | + </reference/method/Session.startTransaction/>` in the Server manual. |
| 77 | + | |
| 78 | + | **Parameter**: ``transactionOptions`` |
| 79 | + |
| 80 | + * - ``abortTransaction()`` |
| 81 | + - | Ends the active transaction for this session. Returns an |
| 82 | + error if there is no active transaction for the session or the |
| 83 | + transaction has been committed or ended. To learn more about |
| 84 | + this method, see the :manual:`abortTransaction() page |
| 85 | + </reference/method/Session.abortTransaction/>` in the Server manual. |
| 86 | + | |
| 87 | + |
| 88 | + * - ``commitTransaction()`` |
| 89 | + - | Commits the active transaction for this session. Returns an |
| 90 | + error if there is no active transaction for the session or if the |
| 91 | + transaction was ended. To learn more about |
| 92 | + this method, see the :manual:`commitTransaction() page |
| 93 | + </reference/method/Session.commitTransaction/>` in the Server manual. |
| 94 | + |
| 95 | + * - ``withTransaction()`` |
| 96 | + - | Starts a transaction on this session and runs the given function within |
| 97 | + a transaction. |
| 98 | + | |
| 99 | + | **Parameters**: ``transactionBody, options`` |
| 100 | + |
| 101 | +Example |
| 102 | +------- |
| 103 | + |
| 104 | +The following example demonstrates how to create a session, create a |
| 105 | +transaction, and insert documents into multiple collections in one transaction |
| 106 | +through the following steps: |
| 107 | + |
| 108 | +1. Create a session from the client by using the ``startSession()`` method. |
| 109 | +#. Use the ``withTransaction()`` method to start a transaction. |
| 110 | +#. Insert multiple documents. The ``withTransaction()`` method runs the |
| 111 | + insert operation and commits the transaction. If any operation results in |
| 112 | + errors, ``withTransaction()`` cancels the transaction. |
| 113 | +#. Close the connection to the server by using the ``client.close()`` method. |
| 114 | + |
| 115 | +.. literalinclude:: /includes/write/transaction.kt |
| 116 | + :start-after: start-transaction |
| 117 | + :end-before: end-transaction |
| 118 | + :language: kotlin |
| 119 | + :copyable: |
| 120 | + :dedent: |
| 121 | + |
| 122 | + |
| 123 | +Additional Information |
| 124 | +---------------------- |
| 125 | + |
| 126 | +To learn more about the concepts mentioned in this guide, see the following pages in |
| 127 | +the Server manual: |
| 128 | + |
| 129 | +- :manual:`Transactions </core/transactions/>` |
| 130 | +- :manual:`Server Sessions </reference/server-sessions>` |
| 131 | +- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>` |
| 132 | + |
| 133 | +To learn more about ACID compliance, see the :website:`What are ACID |
| 134 | +Properties in Database Management Systems? </basics/acid-transactions>` |
| 135 | +article on the MongoDB website. |
| 136 | + |
| 137 | +.. _api-docs-transaction: |
| 138 | + |
| 139 | +API Documentation |
| 140 | +~~~~~~~~~~~~~~~~~ |
| 141 | + |
| 142 | +To learn more about any of the types or methods discussed in this |
| 143 | +guide, see the following API documentation: |
| 144 | + |
| 145 | +- `ClientSession <{+api+}/com.mongodb.kotlin.client/-client-session/index.html>`_ |
| 146 | +- `abortTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/abort-transaction.html>`_ |
| 147 | +- `commitTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/commit-transaction.html>`_ |
| 148 | +- `startTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/start-transaction.html>`_ |
| 149 | +- `withTransaction() <{+api+}/com.mongodb.kotlin.client/-client-session/with-transaction.html>`_ |
0 commit comments