LESSON 12 / 20·2 min readIntermediate

When do I need a transaction?

01 Understand02 Recall03 Prepare

Understand the concept

A transaction makes several database operations commit or roll back as a unit. MongoDB already makes single-document writes atomic, so a transaction is mainly needed when one business rule spans multiple documents. A session supplies transaction context; every participating operation must use that context.

Important ideas

  • A write to one document is atomic; conditional updates often solve simple races.

  • Use a transaction when several document changes must succeed together.

  • Pass the session to every operation; transactions require a suitable replica set or sharded deployment.

  • Keep transactions short and handle retryable failures with the driver's supported transaction pattern; external effects inside retries need special care.

Example — one-document atomic stock update:

JavaScript
// Validate quantity as a positive integer before this operation.
const result = await db.collection('products').updateOne(
  { _id: productId, stock: { $gte: quantity } },
  { $inc: { stock: -quantity } }
);
if (result.matchedCount === 0) {
  throw new Error('Product missing or insufficient stock');
}
  • The filter and decrement are one write. Creating a related reservation in another document may need a transaction too.
PAUSE & RECALL

Can you explain it without the notes?

When do I need a transaction?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

A transaction makes several database operations commit or roll back as a unit. MongoDB already makes single-document writes atomic, so a transaction is mainly needed when one business rule spans multiple documents. A session supplies transaction context; every participating operation must use that context.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • First ask whether a conditional single-document update solves the problem, then explain why a multi-document transaction is necessary if it does not.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: Read concern vs write concern vs read preference?

Adapted from 04_MONGODB_MONGOOSE.md · “When do I need a transaction?”. Examples are study fragments; framework behavior can depend on your version.