All academies
Roadmap
LEVEL 9 · TRANSACTIONS

ACID in MongoDB

12 min read

Single-document operations in MongoDB are always atomic — updating five fields of one document either fully succeeds or fully fails. Because of embedding, this covers most needs. When you must update multiple documents atomically (e.g. debit one account, credit another), use a multi-document transaction.

Using transactions

Transactions run inside a session. Everything between start and commit either all applies or all rolls back.

mongosh
const session = db.getMongo().startSession()
session.startTransaction()
try {
  const accounts = session.getDatabase("bank").accounts
  accounts.updateOne({ _id: "alice" }, { $inc: { balance: -100 } })
  accounts.updateOne({ _id: "bob" },   { $inc: { balance: 100 } })
  session.commitTransaction()
} catch (e) {
  session.abortTransaction()
}

Constraints & costs

Transactions require a replica set (or sharded cluster), hold locks, have a default 60-second lifetime, and add latency. Model your data to make them rare: *embed data that changes together* so single-document atomicity suffices.

Check your understanding

Q1.

Updating multiple fields of a single document requires a transaction to be atomic.

Q2.

What deployment does a multi-document transaction require?

Q3.

What is the best way to REDUCE the need for transactions?