</>
Skip to content
MongoDB lessons (29/38)

MongoDB — Transactions

Basic Transaction

const session = client.startSession();
session.startTransaction();

try {
  db.orders.insertOne({ userId: ObjectId("..."), total: 100 }, { session });
  db.inventory.updateOne({ _id: ObjectId("...") }, { $inc: { stock: -1 } }, { session });
  
  session.commitTransaction();
} catch (error) {
  session.abortTransaction();
} finally {
  session.endSession();
}

Transaction Requirements

RequirementDescription
Replica setRequired for transactions
Storage engineWiredTiger
Time limit60 seconds default

Retry Logic

const session = client.startSession();

for (let retry = 0; retry < 3; retry++) {
  try {
    session.startTransaction();
    // Operations
    await session.commitTransaction();
    break;
  } catch (error) {
    if (error.errorCode === 112) { // WriteConflict
      continue;
    }
    throw error;
  }
}

Mini Practice

  1. Start a transaction
  2. Commit transaction
  3. Abort transaction
  4. Add retry logic

Up Next

Continue with Validation — document validation.

Related Topics

Frequently Asked Questions about Transactions

What is Transactions in MongoDB?

Transactions is a fundamental concept in MongoDB. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Transactions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Transactions.

Why is Transactions important in MongoDB?

Transactions is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.