Performing Multi-Document Transactions

Tutorial 2 of 5

1. Introduction

1.1 Tutorial's Goal

This tutorial aims to provide you with an understanding of how to perform operations on multiple documents within a single transaction. This is an essential skill for maintaining data integrity across complex operations.

1.2 Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand the concept of transactions.
- Initiate a session for multi-document transactions.
- Perform operations on multiple documents within a single transaction.
- Commit and rollback transactions.

1.3 Prerequisites

Before you start, you should have:
- Basic knowledge of MongoDB.
- MongoDB installed on your machine.
- Basic knowledge of Node.js and JavaScript.

2. Step-by-Step Guide

2.1 Concepts

In MongoDB, a transaction is a group of changes that MongoDB performs as a single operation. This means that if any part of the transaction fails, MongoDB cancels the whole transaction, and no change takes effect.

2.2 Examples

Let's consider a banking system where you need to transfer money from one account to another. This operation involves two steps: subtracting the amount from the sender's account and adding it to the receiver's account. If either of these operations fails, the entire operation should be rolled back to maintain data integrity.

2.3 Best Practices

  • Use transactions only when necessary. Single document operations are atomic in MongoDB.
  • Keep the duration of transactions as short as possible to prevent a significant impact on other database operations.

3. Code Examples

3.1 Creating a Transaction

We start by initiating a session:

const session = await mongoose.startSession();

Next, we start a transaction:

session.startTransaction();

Then, perform operations within the transaction:

const opts = { session };  // Include the session in options.
const A = await Account.findOneAndUpdate({name: 'A'}, {$inc: {balance: -100}}, opts);
const B = await Account.findOneAndUpdate({name: 'B'}, {$inc: {balance: 100}}, opts);

Finally, commit the transaction if no error occurs:

await session.commitTransaction();

If an error occurs, abort the transaction:

session.abortTransaction();

3.2 Expected Output

The balance of account 'A' should decrease by 100 and the balance of account 'B' should increase by 100.

4. Summary

In this tutorial, we learned about multi-document transactions in MongoDB. We discussed how to initiate a session, start a transaction, perform operations, and either commit or abort the transaction based on whether an error occurs.

5. Practice Exercises

5.1 Exercise 1

Practice creating a transaction that involves multiple operations on different documents. For example, a transaction could involve updating the price of multiple products in a database.

5.2 Exercise 2

Practice rolling back a transaction when an error occurs. For example, if updating one product fails, all the other updates in the same transaction should be rolled back.

5.3 Exercise 3

Extend Exercise 2 by adding error handling and recovery. If a transaction fails, try to perform the transaction again.

5.4 Solutions and Explanations

Solutions to these exercises involve applying the concepts and code examples presented in this tutorial. If you're stuck, refer back to the code examples and explanations provided.

Happy coding! Practice makes perfect. Keep practicing and exploring more about MongoDB transactions.