MongoDB Transactions
Blog / MongoDB Transactions
5 Minutes Read
By @akash_dathan

MongoDB Transactions

Yes, MongoDB has transaction capability, lack of transaction capability in the earlier versions of MongoDB was one of the major reasons why I was reluctant to use MongoDB. Let’s see how we can use Transactions in MongoDB, before that lets see what exactly is a transaction.


Contents


So, what exactly is a Transaction?

A database transaction is a bunch of database operations grouped together, which has to either happen in full or not at all.

A good example is: transferring money from account A to account B.

There are two operations to be performed so that the transfer is complete

  1. Amount deducted from account A
  2. Amount credited to account B

In this case the transfer is only complete if both the operations are successful. So we either want both of the operations to succeed or none of the operation to succeed so that the money is not lost. This is where a transaction comes into play.

Transactions also makes sure that the data is not tampered with. Let us say account A only has $100, and you try to send $100 to account B and acount C the same time. This will result in one of the transaction to fail because the amount in account A is altered by the succeeding transaction.


Implementing Transaction in MongoDB

Now lets see how we can implement this transaction concept in MongoDB

const session = await connection.startSession();

try {
  await session.withTransaction(async () => {
    // Update account A
    await Account.updateOne(accountAId, { ... });

    // Update account B
    await Account.updateOne(accountBId, { ... });
  });
} catch (error) {
  // Add error handling
} finally {
  // Session has to be ended regardless of error or success
  await session.endSession();
}

Couple of things to note here

  • withTransaction returns a Promise, so we can use an await
  • Everything inside the callback function is considered as one transactional unit.
  • Session has to be ended if the operation succeeds or fails
  • If any one of the operation fails inside the callback, all the other operations are rolled back

That’s all folks, happy hacking 🙌