Lesson 19 / 22

Transactions at a Glance

Multi-document ACID transactions for all-or-nothing updates.

Multi-document ACID

A transaction groups several writes, possibly across collections, so they all succeed together or all roll back.

Sessions & withTransaction

Start a session, then run operations inside withTransaction — it commits automatically or aborts on error.

const session = client.startSession();

await session.withTransaction(async () => {
  await accounts.updateOne({ _id: a }, { $inc: { balance: -100 } }, { session });
  await accounts.updateOne({ _id: b }, { $inc: { balance: 100 } }, { session });
});

Use sparingly

Reach for transactions only when multiple documents truly must succeed or fail together — good schema design (embedding) avoids needing them for most cases.