Group multiple operations in transactions in Azure Cosmos DB for MongoDB vCore
APPLIES TO: MongoDB vCore
It's common to want to group multiple operations into a single transaction to either commit or rollback together. In database principles, transactions typically implement four key ACID principles. ACID stands for:
- Atomicity: Transactions complete entirely or not at all.
- Consistency: Databases transition from one consistent state to another.
- Isolation: Individual transactions are shielded from simultaneous ones.
- Durability: Finished transactions are permanent, ensuring data remains consistent, even during system failures.
The ACID principles in database management ensure transactions are processed reliably. Azure Cosmos DB for MongoDB vCore implements these principles, enabling you to create transactions for multiple operations.
Prerequisites
- An existing Azure Cosmos DB for MongoDB vCore cluster.
- If you don't have an Azure subscription, create an account for free.
- If you have an existing Azure subscription, create a new Azure Cosmos DB for MongoDB vCore cluster.
Create a transaction
Create a new transaction using the appropriate methods from the developer language of your choice. These methods typically include some wrapping mechanism to group multiple transactions together, and a method to commit the transaction.
Note
The samples in this section assume you have a collection variable named collection
.
Use
startSession()
to create a client session for the transaction operation.const transactionSession = client.startSession();
Create a transaction using
withTransaction()
and place all relevant transaction operations within the callback.await transactionSession.withTransaction(async () => { await collection.insertOne({ name: "Coolarn shirt", price: 38.00 }, transactionSession); await collection.insertOne({ name: "Coolarn shirt button", price: 1.50 }, transactionSession); });
Commit the transaction using
commitTransaction()
.transactionSession.commitTransaction();
Use
endSession()
to end the transaction session.transactionSession.endSession();
Roll back a transaction
Occasionally, you may be required to undo a transaction before it's committed.
Using an existing transaction session, abort the transaction with
abortTransaction()
.transactionSession.abortTransaction();
End the transaction session.
transactionSession.endSession();