WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

MongoDB · Expert · question 64 of 100

Discuss the pros and cons of using multi-document transactions in MongoDB, and when they should be used.?

📕 Buy this interview preparation book: 100 MongoDB questions & answers — PDF + EPUB for $5

Multi-document transactions in MongoDB allow the user to group multiple operations together and either commit them all at once or roll them all back if any of the operations fail. These transactions can span multiple documents and even multiple collections or databases. While there are certainly advantages to using multi-document transactions, there are also drawbacks that must be taken into consideration.

Pros: 1. Atomic operations: Multi-document transactions guarantee that all operations are completed or none are. This means that if any part of the transaction fails, all changes are rolled back to their previous state, ensuring data consistency.

2. Availability: In previous versions of MongoDB, transactions were only available on replica sets. However, with the release of MongoDB 4.2, transactions are now available in sharded clusters as well, allowing for greater flexibility and scalability.

3. Simplified code logic: By grouping multiple operations together, the code logic can be simplified and the number of database calls can be reduced. This can lead to better performance and reduced complexity.

Cons: 1. Performance: Multi-document transactions may not perform as well as single-document operations, especially for large or complex transactions. Transactions require locking of resources during the transaction, which can cause contention and reduce overall performance. Additionally, transactions are limited to a single replica set or shard, which can also impact performance.

2. Data throughput: Multi-document transactions require more data to be sent between the client and the database. This can reduce data throughput, causing slower response times.

3. Limitations: Multi-document transactions have some limitations, including the inability to perform an operation in multiple shards, and the inability to perform transactions on some types of operations (including map-reduce and text search). Additionally, transactions have a limit on the number of documents they can operate on (currently set at 1,000).

When to use multi-document transactions: Multi-document transactions are most commonly used in situations where data consistency is critical, such as financial transactions or other scenarios where incomplete transactions could cause problems. Additionally, they can be used in cases where simplifying code logic or reducing the number of database calls will lead to improved performance. However, it is important to carefully consider the drawbacks and limitations of multi-document transactions before implementing them, and to test for performance and scalability before deploying them in production environments.

Example usage code of transactions in MongoDB:

const session = client.startSession();
session.startTransaction();
try {
  const usersCollection = client.db("test").collection("users");
  const accountsCollection = client.db("test").collection("accounts");

  await usersCollection.updateOne(
    { _id: userId },
    { $inc: { balance: amount } },
    { session }
  );

  await accountsCollection.updateOne(
    { _id: accountId },
    { $inc: { balance: -amount } },
    { session }
  );

  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
  throw error;
} finally {
  session.endSession();
}

In this example code, a session is started to begin a transaction. Two collections, "users" and "accounts," are updated within the same transaction using the ‘updateOne‘ method. If any part of the transaction fails, the entire transaction is rolled back by calling ‘abortTransaction()‘. If all operations are successful, the transaction is committed, and the changes are saved to the database by calling ‘commitTransaction()‘. Finally, the session is ended.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic MongoDB interview — then scores it.
📞 Practice MongoDB — free 15 min
📕 Buy this interview preparation book: 100 MongoDB questions & answers — PDF + EPUB for $5

All 100 MongoDB questions · All topics