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

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.

  1. Use startSession() to create a client session for the transaction operation.

    const transactionSession = client.startSession();
    
  2. 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);
    });
    
  3. Commit the transaction using commitTransaction().

    transactionSession.commitTransaction();
    
  4. 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.

  1. Using an existing transaction session, abort the transaction with abortTransaction().

    transactionSession.abortTransaction();
    
  2. End the transaction session.

    transactionSession.endSession();
    

Next step