MongoDB ACID Transactions as Multi-Document Transactions

Views: 608
Comments: 0
Like/Unlike: 0
Posted On: 08-Jul-2023 02:00 

Share:   fb twitter linkedin
mongo
Participant
84 Points
8 Posts


In MongoDB, a transaction is a sequence of read and write operations performed on the database that should be treated as a single atomic unit of work. Transactions ensure data integrity by guaranteeing that either all operations within the transaction are applied or none of them are. 

MongoDB supports multi-document transactions starting from version 4.0. Transactions are typically used when you need to perform multiple operations that depend on each other and should be applied together to maintain data consistency.

Here's an example of how you can perform a transaction in MongoDB using the official MongoDB Node.js driver:

const { MongoClient } = require('mongodb');

async function performTransaction() {
  const uri = 'mongodb://localhost:27017';
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const session = client.startSession();

    // Start the transaction
    session.startTransaction();

    const productsCollection = client.db('yourDatabase').collection('products');
    const ordersCollection = client.db('yourDatabase').collection('orders');

    // Perform operations within the transaction
    const result1 = await productsCollection.insertOne({ name: 'Product 1', price: 10 });
    const result2 = await ordersCollection.insertOne({ productId: result1.insertedId, quantity: 5 });

    // Commit the transaction
    await session.commitTransaction();

    console.log('Transaction committed successfully.');
  } catch (error) {
    console.error('Error occurred during transaction. Rolling back.', error);

    // Rollback the transaction
    await session.abortTransaction();
  } finally {
    session.endSession();
    client.close();
  }
}

performTransaction();

 

In this example, following are happening:

  1. connect to the MongoDB server,
  2. start a session, and
  3. begin the transaction.
  4. then perform multiple operations (inserting a product and an order) within the transaction.
  5. If all the operations succeed, we commit the transaction. Otherwise, if an error occurs, we rollback the transaction to undo any changes made within it.

 

It's important to note that transactions in MongoDB are only available for replica sets and sharded clusters. Standalone MongoDB instances do not support transactions. Additionally, transactions may incur performance overhead, so they should be used judiciously for critical operations where data consistency is paramount.

 

0 Comments
 Log In to Chat