Overview
In this guide, you can learn how to use the Kotlin driver to perform transactions. 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 session is a grouping of related read or write operations that you intend to run sequentially. Sessions enable causal consistency for a group of operations or allow you to execute operations in an ACID transaction. MongoDB guarantees that the data involved in your transaction operations remains consistent, even if the operations encounter unexpected errors.
When using the Kotlin driver, you can create a new session from a
MongoClient 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 ClientSession only with the MongoClient (or associated
MongoDatabase or MongoCollection) that created it. Using a
ClientSession with a different MongoClient results in operation
errors.
Causal Consistency
MongoDB enables causal consistency in certain client sessions. The causal consistency model guarantees that in a distributed system, operations within a session run in a causal order. Clients observe results that are consistent with the causal relationships, or the dependencies between operations. For example, if you perform a series of operations where one operation logically depends on the result of another, any subsequent reads reflect the dependent relationship.
To guarantee causal consistency, client sessions must fulfill the following requirements:
When starting a session, the driver must enable the causal consistency option. This option is enabled by default.
Operations must run in a single session on a single thread. Otherwise, the sessions or threads must communicate the operation time and cluster time values to each other. To view an example of two sessions that communicate these values, see the Causal Consistency examples in the MongoDB server manual.
You must use a
ReadConcern.MAJORITYread concern.You must use a
WriteConcern.MAJORITYwrite concern. This is the default write concern value.
The following table describes the guarantees that causally consistent sessions provide:
Guarantee | Description |
|---|---|
Read your writes | Read operations reflect the results of preceding write operations. |
Monotonic reads | Read operations do not return results that reflect an earlier data state than a preceding read operation. |
Monotonic writes | If a write operation must precede other write operations, the server runs this write operation first. For example, if you call |
Writes follow reads | If a write operation must follow other read operations, the server runs the read operations first. For example, if you call |
Tip
To learn more about the concepts mentioned in this section, see the following MongoDB server manual entries:
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:
Method | Description |
|---|---|
| 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). |
| 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. |
| 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. |
Tip
Transaction Timeout
You can set a limit on amount of time that operations can take to complete in your transactions. To learn more, see the Transactions section of the Limit Server Execution Time guide.
A ClientSession also has methods to retrieve session properties and modify
mutable session properties. View the API documentation
to learn more about these methods.
Example
This example uses the following Kotlin data class to model its documents:
data class Account( val accountId: String, val amount: Int )
The following example demonstrates how you can create a session, create a transaction, and commit changes to existing documents:
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, orabortTransaction()if any operations fail.
// Set up the session val session = client.startSession() try { session.startTransaction() val savingsColl = database .getCollection<Account>("savings_accounts") val checkingColl = database .getCollection<Account>("checking_accounts") savingsColl.findOneAndUpdate( session, eq(Account::accountId.name, "9876"), inc(Account::amount.name, -100), ) checkingColl.findOneAndUpdate( session, eq(Account::accountId.name, "9876"), inc(Account::amount.name, 100) ) // Commit the transaction val result = session.commitTransaction() println("Transaction committed.") } catch (error: Exception) { println("An error occurred during the transaction: ${error.message}") // Abort the transaction session.abortTransaction() }
Note
Parallel Operations Not Supported
The Kotlin driver does not support running parallel operations within a single transaction.
If you're using MongoDB server v8.0 or later, you can perform write operations on multiple namespaces within a single transaction by using bulk write operations. To learn more, see the Bulk Operations guide.
Additional Information
To learn more about the concepts mentioned in this guide, see the following pages in the Server manual:
To learn more about ACID compliance, see the What are ACID Properties in Database Management Systems? 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: