Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DOCSP-41760 Add transactions page #167

Merged
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions source/examples/generated/TransactionsTest.snippet.transaction.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Set up the MongoDB client and get the collection
suspend fun performTransaction(client: MongoClient) {
client.startSession().use { session ->
session.startTransaction() // Start the transaction
stephmarie17 marked this conversation as resolved.
Show resolved Hide resolved
try {
val database = client.getDatabase("bank")

val savingsColl = database.getCollection<SavingsAccount>("savings_accounts")
savingsColl.findOneAndUpdate(
session,
SavingsAccount::accountId eq "9876",
inc(SavingsAccount::amount, -100)
)

val checkingColl = database.getCollection<CheckingAccount>("checking_accounts")
checkingColl.findOneAndUpdate(
session,
CheckingAccount::accountId eq "9876",
inc(CheckingAccount::amount, 100)
)
// Commit the transaction
stephmarie17 marked this conversation as resolved.
Show resolved Hide resolved
session.commitTransaction()
println("Transaction committed.")
} catch (error: Exception) {
println("An error occurred during the transaction: ${error.message}")
// Abort the transaction
session.abortTransaction()
}
}
}

data class SavingsAccount(val accountId: String, val amount: Int)
data class CheckingAccount(val accountId: String, val amount: Int)
stephmarie17 marked this conversation as resolved.
Show resolved Hide resolved

fun main() = runBlocking {
val uri = "<connection string uri>"
val client = MongoClient.create(uri)
performTransaction(client)
}
stephmarie17 marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions source/fundamentals.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Fundamentals
/fundamentals/aggregation
/fundamentals/aggregation-expression-operations
/fundamentals/indexes
/fundamentals/transactions
/fundamentals/collations
/fundamentals/logging
/fundamentals/monitoring
Expand Down
126 changes: 126 additions & 0 deletions source/fundamentals/transactions.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
.. _kotlin-fundamentals-transactions:

============
Transactions
============

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: modify, customize

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

In this guide, you can learn how to use the {+driver-short+} to perform
**transactions**. :manual:`Transactions </core/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
:manual:`session </reference/server-sessions/>` is a grouping of related
read or write operations that you intend to run sequentially. Sessions
enable :manual:`causal consistency
</core/read-isolation-consistency-recency/#causal-consistency>` for a
group of operations or allow you to execute operations in an
:website:`ACID transaction </basics/acid-transactions>`. 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
``Client`` instance as a ``ClientSession``. We recommend that you reuse
your client for multiple sessions and transactions instead of
instantiating a new client each time.

.. warning::

Use a ``Session`` only with the ``Client`` (or associated
``Database`` or ``Collection``) that created it. Using a
``Session`` with a different ``Client`` results in operation
errors.

Methods
-------

Create a ``ClientSession`` by using the ``startSession()`` method on your
``Client`` instance. You can then modify the session state by using the
following methods:

.. list-table::
:widths: 25 75
:header-rows: 1

* - Method
- Description

* - ``startTransaction()``
- | Starts a new transaction for this session with the
default transaction options. You cannot start a
transaction if there's already an active transaction
on the session.
|
| To set transaction options, use ``startTransaction(transactionOptions: TransactionOptions)``.

* - ``abortTransaction()``
- | Ends the active transaction for this session. Returns an error
if there is no active transaction for the
session or the transaction was previously ended.

* - ``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.

A ``Session`` also has methods to retrieve session properties and modify
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>`__
to learn more about these methods.

Example
-------

The following example demonstrates how you can create a session, create a transaction,
and commit a changes to existing documents:

1. Create a session from the client using the ``startSession()`` method.
#. Use the ``startTransaction()`` method to start a transaction.
#. Update the specified documents, then use the ``commitTransaction()`` method if all
operations succeed, or ``abortTransaction()`` if any operations fail.

.. literalinclude:: /examples/generated/TransactionsTest.snippet.transaction.kt
:language: kotlin
:copyable:

Additional Information
----------------------

To learn more about the concepts mentioned in this guide, see the following pages in
the Server manual:

- :manual:`Transactions </core/transactions/>`
- :manual:`Server Sessions </reference/server-sessions>`
- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>`

To learn more about ACID compliance, see the :website:`What are ACID
Properties in Database Management Systems? </basics/acid-transactions>`
article on the MongoDB website.

API Documentation
~~~~~~~~~~~~~~~~~

To learn more about any of the types or methods discussed in this
guide, see the following API Documentation:

- `ClientSession <{+api+}/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/index.html>`__
- `startTransaction <{+api+}/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/start-transaction.html>`__
- `commitTransaction <{+api+}/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/commit-transaction.html>`__
- `abortTransaction <{+api+}/apidocs/mongodb-driver-kotlin-coroutine/mongodb-driver-kotlin-coroutine/com.mongodb.kotlin.client.coroutine/-client-session/abort-transaction.html>`__
Loading