MongoDB & MongooseInterview preparation
Intermediate·Concept·2 min read

When do I need a transaction?

Practice this question

Definition:

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.

Key points:

  • 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.

Interview point:

  • First ask whether a conditional single-document update solves the problem, then explain why a multi-document transaction is necessary if it does not.
Adapted from 04_MONGODB_MONGOOSE.md · “When do I need a transaction?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.