Skip to content

Commit af1fdaa

Browse files
committed
add transactions page
1 parent 2390577 commit af1fdaa

File tree

3 files changed

+171
-0
lines changed

3 files changed

+171
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Set up the MongoDB client and get the collection
2+
suspend fun performTransaction(client: CoroutineClient) {
3+
client.startSession().use { session: ClientSession ->
4+
session.startTransaction() // Start the transaction
5+
try {
6+
val database = client.getDatabase("bank")
7+
8+
val savingsColl = database.getCollection<SavingsAccount>("savings_accounts")
9+
savingsColl.findeOneAndUpdate(
10+
session,
11+
SavingsAccount::accountId eq "9876",
12+
inc(SavingsAccount::amount, -100)
13+
)
14+
15+
val checkingColl = database.getCollection<CheckingAccount>("checking_accounts")
16+
checkingColl.findOneAndUpdate(
17+
session,
18+
CheckingAccount::accountId eq "9876",
19+
inc(CheckingAccount::amount, 100)
20+
)
21+
// Commit the transaction
22+
session.commitTransaction()
23+
println("Transaction committed.")
24+
} catch (error: Exception) {
25+
println("An error occurred during the transaction: ${error.message}")
26+
session.abortTransaction() // Abort the transaction
27+
} finally {
28+
session.endSession() // End the session
29+
}
30+
}
31+
}
32+
33+
data class SavingsAccount(val accountId: String, val amount: Int)
34+
data class CheckingAccount(val accountId: String, val amount: Int)
35+
36+
fun main() = runBlocking {
37+
val uri = "<connection string uri>"
38+
val client = MongoClient.create(uri)
39+
performTransaction(client)
40+
}

source/fundamentals.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Fundamentals
1919
/fundamentals/aggregation
2020
/fundamentals/aggregation-expression-operations
2121
/fundamentals/indexes
22+
/fundamentals/transactions
2223
/fundamentals/collations
2324
/fundamentals/logging
2425
/fundamentals/monitoring

source/fundamentals/transactions.txt

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
.. _kotlin-fundamentals-transactions:
2+
3+
============
4+
Transactions
5+
============
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: modify, customize
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+driver-short+} to perform
24+
**transactions**. :manual:`Transactions </core/transactions/>` allow
25+
you to run a series of operations that do not change any data until the
26+
transaction is committed. If any operation in the transaction returns an
27+
error, the driver cancels the transaction and discards all data changes
28+
before they ever become visible.
29+
30+
In MongoDB, transactions run within logical **sessions**. A
31+
:manual:`session </reference/server-sessions/>` is a grouping of related
32+
read or write operations that you intend to run sequentially. Sessions
33+
enable :manual:`causal consistency
34+
</core/read-isolation-consistency-recency/#causal-consistency>` for a
35+
group of operations or allow you to execute operations in an
36+
:website:`ACID transaction </basics/acid-transactions>`. MongoDB
37+
guarantees that the data involved in your transaction operations remains
38+
consistent, even if the operations encounter unexpected errors.
39+
40+
When using the {+driver-short+}, you can create a new session from a
41+
``Client`` instance as a ``ClientSession``. We recommend that you reuse
42+
your client for multiple sessions and transactions instead of
43+
instantiating a new client each time.
44+
45+
.. warning::
46+
47+
Use a ``Session`` only with the ``Client`` (or associated
48+
``Database`` or ``Collection``) that created it. Using a
49+
``Session`` with a different ``Client`` results in operation
50+
errors.
51+
52+
Methods
53+
-------
54+
55+
Create a ``ClientSession`` by using the ``startSession()`` method on your
56+
``Client`` instance. You can then modify the session state by using the
57+
following methods:
58+
59+
.. list-table::
60+
:widths: 25 75
61+
:header-rows: 1
62+
63+
* - Method
64+
- Description
65+
66+
* - ``startTransaction()``
67+
- | Starts a new transaction for this session with the
68+
default transaction options. You cannot start a
69+
transaction if there's already an active transaction
70+
on the session.
71+
|
72+
| To set transaction options, use ``startTransaction(transactionOptions: TransactionOptions)``.
73+
74+
* - ``abortTransaction()``
75+
- | Ends the active transaction for this session. Returns an error
76+
if there is no active transaction for the
77+
session or the transaction was previously ended.
78+
79+
* - ``commitTransaction()``
80+
- | Commits the active transaction for this session. Returns an
81+
error if there is no active transaction for the session or if the
82+
transaction was ended.
83+
84+
* - ``endSession()``
85+
- | Ends any existing transactions and closes the session.
86+
87+
A ``Session`` also has methods to retrieve session properties and modify
88+
mutable session properties. View the `API documentation<{+api+/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/index.html>`__
89+
to learn more about these methods.
90+
91+
Example
92+
-------
93+
94+
The following example demonstrates how you can create a session, create a transaction,
95+
and commit a changes to existing documents:
96+
97+
1. Create a session from the client using the ``startSession()`` method.
98+
#. Use the ``startTransaction()`` method to start a transaction.
99+
#. Update the specified documents, then use the ``commitTransaction()`` method if all
100+
operations succeed, or ``abortTransaction()`` if any operations fail.
101+
102+
.. literalinclude:: /examples/generated/TransactionsTest.snippet.transaction.kt
103+
:start-after: start-data-class
104+
:end-before: end-data-class
105+
:language: kotlin
106+
:copyable:
107+
108+
Additional Information
109+
----------------------
110+
111+
To learn more about the concepts mentioned in this guide, see the following pages in
112+
the Server manual:
113+
114+
- :manual:`Transactions</core/transactions/>`
115+
- :manual:`Server Sessions</reference/server-sessions>`
116+
- :manual:`/core/read-isolation-consistency-recency/#causal-consistency`
117+
118+
To learn more about ACID compliance, see the `What are ACID properties in Database Management Systems?<https://www.mongodb.com/resources/basics/databases/acid-transactions?tck=docs>`
119+
article on the MongoDB website.
120+
121+
API Documentation
122+
~~~~~~~~~~~~~~~~~
123+
124+
To learn more about any of the types or methods discussed in this
125+
guide, see the following API Documentation:
126+
127+
- `ClientSession<{+api+/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/index.html}>`__
128+
- `startTransaction<{+api+/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/start-transaction.html}>`__
129+
- `commitTransaction<{+api+/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/commit-transaction.html}>`__
130+
- `abortTransaction<{+api+/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/abort-transaction.html}>`__

0 commit comments

Comments
 (0)