Bird
Raised Fist0
MongoDBquery~5 mins

Multi-document transactions in MongoDB

Choose your learning style10 modes available
Introduction
Multi-document transactions let you change many pieces of data at once, and make sure all changes happen together or none at all. This keeps your data safe and correct.
When you need to update several documents and want all updates to succeed or fail as one group.
When transferring money between two accounts and both accounts must update together.
When creating an order and reducing stock quantity at the same time.
When deleting related data from multiple collections and want to avoid partial deletions.
Syntax
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  // your operations here
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
You must start a session before starting a transaction.
Always commit or abort the transaction to finish it properly.
Examples
This example inserts a document in one collection and updates another, all inside a transaction.
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  await collection1.insertOne({name: 'Alice'}, {session});
  await collection2.updateOne({name: 'Bob'}, {$inc: {score: 10}}, {session});
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
This example transfers money between two users, ensuring both updates happen together.
MongoDB
const session = client.startSession();
session.startTransaction();
try {
  await accounts.updateOne({user: 'John'}, {$inc: {balance: -100}}, {session});
  await accounts.updateOne({user: 'Jane'}, {$inc: {balance: 100}}, {session});
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  session.endSession();
}
Sample Program
This program creates two accounts, then transfers 200 from Alice to Bob inside a transaction. It prints the final balances.
MongoDB
const { MongoClient } = require('mongodb');

async function run() {
  const client = new MongoClient('mongodb://localhost:27017');
  await client.connect();
  const db = client.db('bank');
  const accounts = db.collection('accounts');

  // Prepare accounts
  await accounts.deleteMany({});
  await accounts.insertMany([
    { user: 'Alice', balance: 500 },
    { user: 'Bob', balance: 300 }
  ]);

  const session = client.startSession();

  try {
    session.startTransaction();

    // Alice sends 200 to Bob
    await accounts.updateOne({ user: 'Alice' }, { $inc: { balance: -200 } }, { session });
    await accounts.updateOne({ user: 'Bob' }, { $inc: { balance: 200 } }, { session });

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

  const results = await accounts.find().toArray();
  console.log(results);
  await client.close();
}

run();
OutputSuccess
Important Notes
Transactions work only on replica sets or sharded clusters, not standalone servers.
Always pass the session object to your operations inside the transaction.
Keep transactions short to avoid locking resources for too long.
Summary
Multi-document transactions let you group multiple changes so they all succeed or fail together.
You start a session, begin a transaction, do your operations, then commit or abort.
Use transactions to keep your data consistent when changing many documents.

Practice

(1/5)
1. What is the main purpose of using multi-document transactions in MongoDB?
easy
A. To create indexes automatically
B. To speed up single document queries
C. To ensure multiple document changes succeed or fail together
D. To backup the database

Solution

  1. Step 1: Understand transaction purpose

    Transactions group multiple operations so they either all succeed or all fail, ensuring data consistency.
  2. Step 2: Compare options

    Only To ensure multiple document changes succeed or fail together describes this behavior. Other options describe unrelated features.
  3. Final Answer:

    To ensure multiple document changes succeed or fail together -> Option C
  4. Quick Check:

    Transaction purpose = group changes atomically [OK]
Hint: Transactions group multiple changes to keep data consistent [OK]
Common Mistakes:
  • Confusing transactions with indexing
  • Thinking transactions speed up single queries
  • Assuming transactions create backups
2. Which of the following is the correct way to start a transaction in a MongoDB session using the Node.js driver?
easy
A. db.transactionStart()
B. session.startTransaction()
C. session.begin()
D. start.sessionTransaction()

Solution

  1. Step 1: Recall MongoDB transaction syntax

    The correct method to start a transaction on a session is startTransaction().
  2. Step 2: Eliminate incorrect options

    Options A, B, and D are not valid MongoDB session methods.
  3. Final Answer:

    session.startTransaction() -> Option B
  4. Quick Check:

    Start transaction method = startTransaction() [OK]
Hint: Use session.startTransaction() to begin a transaction [OK]
Common Mistakes:
  • Using incorrect method names like begin()
  • Calling transaction methods on db instead of session
  • Mixing method order or syntax
3. Consider this MongoDB transaction code snippet in Node.js:
const session = client.startSession();
session.startTransaction();
await collection1.insertOne({item: 'apple'}, {session});
await collection2.updateOne({item: 'banana'}, {$inc: {qty: 1}}, {session});
await session.commitTransaction();
session.endSession();
console.log('Transaction complete');
What will be printed if both operations succeed?
medium
A. Transaction complete
B. Transaction aborted
C. Error: session not started
D. No output

Solution

  1. Step 1: Analyze transaction flow

    The code starts a session, begins a transaction, performs two operations, commits the transaction, ends the session, then logs a message.
  2. Step 2: Determine output on success

    If both operations succeed and commitTransaction() completes without error, the console.log will print 'Transaction complete'.
  3. Final Answer:

    Transaction complete -> Option A
  4. Quick Check:

    Successful commit logs 'Transaction complete' [OK]
Hint: If commitTransaction succeeds, console logs 'Transaction complete' [OK]
Common Mistakes:
  • Assuming commitTransaction logs automatically
  • Confusing session start errors with commit success
  • Ignoring async/await behavior
4. You wrote this MongoDB transaction code but it throws an error:
const session = client.startSession();
session.startTransaction;
await collection.insertOne({name: 'John'}, {session});
await session.commitTransaction();
session.endSession();
What is the error and how to fix it?
medium
A. insertOne does not accept session option
B. session.endSession() should be called before commitTransaction()
C. session.startSession() should be awaited
D. Missing parentheses on startTransaction; use session.startTransaction()

Solution

  1. Step 1: Identify the syntax error

    The code calls session.startTransaction without parentheses, so the function is not executed.
  2. Step 2: Correct the method call

    Add parentheses to call the function: session.startTransaction().
  3. Final Answer:

    Missing parentheses on startTransaction; use session.startTransaction() -> Option D
  4. Quick Check:

    Method calls need parentheses () [OK]
Hint: Always add () to call methods like startTransaction() [OK]
Common Mistakes:
  • Forgetting parentheses on method calls
  • Calling endSession before commitTransaction
  • Thinking startSession is async and needs await
5. You want to update two collections atomically: deduct 10 from accounts.balance and add 10 to transactions.amount. Which transaction code snippet correctly ensures both updates succeed or fail together?
hard
A. const session = client.startSession(); session.startTransaction(); await accounts.updateOne({user: 'A'}, {$inc: {balance: -10}}, {session}); await transactions.updateOne({user: 'A'}, {$inc: {amount: 10}}, {session}); await session.commitTransaction(); session.endSession();
B. await accounts.updateOne({user: 'A'}, {$inc: {balance: -10}}); await transactions.updateOne({user: 'A'}, {$inc: {amount: 10}});
C. const session = client.startSession(); await accounts.updateOne({user: 'A'}, {$inc: {balance: -10}}, {session}); await transactions.updateOne({user: 'A'}, {$inc: {amount: 10}}, {session}); session.commitTransaction(); session.endSession();
D. const session = client.startSession(); session.startTransaction(); accounts.updateOne({user: 'A'}, {$inc: {balance: -10}}, {session}); transactions.updateOne({user: 'A'}, {$inc: {amount: 10}}, {session}); session.commitTransaction(); session.endSession();

Solution

  1. Step 1: Check transaction start and commit

    const session = client.startSession(); session.startTransaction(); await accounts.updateOne({user: 'A'}, {$inc: {balance: -10}}, {session}); await transactions.updateOne({user: 'A'}, {$inc: {amount: 10}}, {session}); await session.commitTransaction(); session.endSession(); correctly calls startTransaction() and commitTransaction() on the session.
  2. Step 2: Verify operations use session and await

    const session = client.startSession(); session.startTransaction(); await accounts.updateOne({user: 'A'}, {$inc: {balance: -10}}, {session}); await transactions.updateOne({user: 'A'}, {$inc: {amount: 10}}, {session}); await session.commitTransaction(); session.endSession(); uses await on both update operations and passes the session option, ensuring atomicity.
  3. Step 3: Identify errors in other options

    await accounts.updateOne({user: 'A'}, {$inc: {balance: -10}}); await transactions.updateOne({user: 'A'}, {$inc: {amount: 10}}); lacks transaction usage. const session = client.startSession(); await accounts.updateOne({user: 'A'}, {$inc: {balance: -10}}, {session}); await transactions.updateOne({user: 'A'}, {$inc: {amount: 10}}, {session}); session.commitTransaction(); session.endSession(); misses startTransaction(). const session = client.startSession(); session.startTransaction(); accounts.updateOne({user: 'A'}, {$inc: {balance: -10}}, {session}); transactions.updateOne({user: 'A'}, {$inc: {amount: 10}}, {session}); session.commitTransaction(); session.endSession(); misses await on operations.
  4. Final Answer:

    Option A code snippet -> Option A
  5. Quick Check:

    Start, await ops with session, commit = correct transaction [OK]
Hint: Start transaction, await ops with session, then commit [OK]
Common Mistakes:
  • Not awaiting async operations inside transaction
  • Forgetting to start the transaction
  • Running operations outside session context
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard