LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 3817 min read

Transactions in MongoDB

Group multiple operations across documents (or collections) into one all-or-nothing multi-document ACID transaction.

Single-Document Atomicity vs Transactions

Every single-document write in MongoDB has always been atomic — an update either fully applies or doesn't apply at all, even across multiple fields. A transaction extends that same all-or-nothing guarantee across multiple documents, and even multiple collections, in one logical unit of work.

Starting a Session and Transaction

A transaction requires a session, and withTransaction wraps a block of operations, automatically committing on success or aborting (rolling back) on any error.

const session = await mongoose.startSession();
try {
await session.withTransaction(async () => {
await Account.updateOne({ _id: fromId }, { $inc: { balance: -100 } }, { session });
await Account.updateOne({ _id: toId }, { $inc: { balance: 100 } }, { session });
});
} finally {
await session.endSession();
}

A Practical Example: Transferring Funds

Transferring money between two accounts is the textbook transaction example: if the deduction from one account succeeds but the credit to the other fails, you never want the deduction to stick around on its own — the transaction ensures both happen, or neither does.

Every Operation Must Pass { session }

Forgetting to pass the session option to an operation inside withTransaction means that operation runs outside the transaction entirely — it won't be rolled back if something else in the block fails.

When You Actually Need Transactions

Transactions add real overhead, and MongoDB's general design philosophy (embedding related data) already avoids needing them in many cases a relational database would require one. Reach for a transaction specifically when an operation must atomically span multiple documents or collections, and a schema redesign (more embedding) genuinely can't avoid that need.

Reasonable to Use a Transaction

  • Transferring value between two separate account documents
  • Creating an order and simultaneously decrementing inventory across collections
  • Any operation that must not partially apply

Consider Redesigning the Schema Instead

  • Updating a post and one of its embedded comments (already atomic as one document)
  • Frequent multi-document transactions on a hot path — may indicate embedding would serve better

Common Beginner Mistakes

Reaching for a transaction before considering embedding

Many apparent needs for a multi-document transaction disappear entirely if the data is instead modeled as one embedded document, which is already atomic by default.

Forgetting to call endSession()

Always release a session when you're done with it, typically in a finally block, to avoid leaking session resources.

FAQs

Yes — multi-document transactions require MongoDB to be running as a replica set (or sharded cluster), which is exactly what MongoDB Atlas provisions by default, even on the free tier.

Yes, meaningfully — they involve additional coordination overhead, which is exactly why MongoDB's document model favors avoiding the need for them through good schema design where possible.

Summary

Transactions extend MongoDB's always-atomic single-document guarantee across multiple documents, at some performance cost — reach for them when genuinely needed, not as a default. Next, you'll learn replication, MongoDB's mechanism for data redundancy and high availability.

Next Lesson →

Replication & Replica Sets