Docs Menu
Docs Home
/ / /
Kotlin Coroutine
/

Transactions

On this page

  • Overview
  • Methods
  • Example
  • Additional Information
  • API Documentation

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.

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
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 ClientSession also has methods to retrieve session properties and modify mutable session properties. View the API documentation to learn more about these methods.

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:

  1. Create a session from the client using the startSession() method.

  2. Use the startTransaction() method to start a transaction.

  3. Update the specified documents, then use the commitTransaction() method if all operations succeed, or abortTransaction() 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()
}

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.

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

Back

Indexes

Next

Collations