Skip to content

Commit 7809afb

Browse files
committed
add new page and code example
1 parent 14c04d9 commit 7809afb

File tree

3 files changed

+204
-0
lines changed

3 files changed

+204
-0
lines changed

source/includes/write/transaction.kt

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import com.mongodb.*
2+
import com.mongodb.client.ClientSession
3+
import com.mongodb.client.MongoClients
4+
import com.mongodb.client.MongoCollection
5+
import org.bson.Document
6+
7+
fun main() {
8+
// start-transaction
9+
// Creates a new MongoClient with a connection string
10+
val client = MongoClients.create("<connection string>")
11+
12+
// Gets the database and collection
13+
val restaurantsDb = client.getDatabase("sample_restaurants")
14+
val restaurantsCollection: MongoCollection<Document> = restaurantsDb.getCollection("restaurants")
15+
16+
fun insertDocuments(session: ClientSession) {
17+
// Sets options for the collection operation within the transaction
18+
val restaurantsCollectionWithOptions = restaurantsCollection
19+
.withWriteConcern(WriteConcern("majority"))
20+
.withReadConcern(ReadConcern.LOCAL)
21+
22+
// Inserts documents within the transaction
23+
restaurantsCollectionWithOptions.insertOne(
24+
session,
25+
Document("name", "Kotlin Sync Pizza").append("cuisine", "Pizza")
26+
)
27+
restaurantsCollectionWithOptions.insertOne(
28+
session,
29+
Document("name", "Kotlin Sync Burger").append("cuisine", "Burger")
30+
)
31+
}
32+
33+
// Starts a client session
34+
client.startSession().use { session ->
35+
try {
36+
val txnOptions = TransactionOptions.builder()
37+
.readConcern(ReadConcern.LOCAL)
38+
.writeConcern(WriteConcern.MAJORITY)
39+
.build()
40+
41+
// Use the withTransaction method to start a transaction and execute the lambda function
42+
session.withTransaction({
43+
insertDocuments(session)
44+
println("Transaction succeeded")
45+
}, txnOptions)
46+
} catch (e: Exception) {
47+
println("Transaction failed: ${e.message}")
48+
}
49+
}
50+
51+
// Closes the MongoClient
52+
client.close()
53+
// end-transaction
54+
}

source/write-operations.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ Write Data to MongoDB
2727
/write/replace
2828
/write/delete
2929
/write/bulk-write
30+
/write/transactions
3031

3132
..
3233
/write/gridfs

source/write/transactions.txt

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
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

Comments
 (0)