MongoDB Transactions

Intermediate
9 min read
Updated: Nov 2026
Getting Started

What Is Transactions?

A write to a single document is always atomic in MongoDB. When a change must span several documents or collections and succeed or fail together, you use a multi-document transaction. Transactions are available on replica sets (and sharded clusters) and run inside a session. They provide ACID guarantees: all operations in the transaction commit together, or none of them do.

Why It Matters

ReasonBenefit
All-or-nothing changesMoving money between accounts either updates both balances or neither.
Consistent readsReads inside a transaction see a consistent snapshot of the data.
Familiar semanticsACID behavior matches what developers expect from relational databases.
Works across collectionsA transaction can touch many collections in the same replica set.

How To Use It

  1. Run mongosh against a replica set, such as an Atlas cluster or a local one started with --replSet.
  2. Create a session with db.getMongo().startSession().
  3. Get collection handles from the session: session.getDatabase("bank").accounts.
  4. Call session.startTransaction() with the options you need.
  5. Perform the related writes using the session's handles.
  6. Call commitTransaction() when all succeed, or abortTransaction() on any error.
  7. Call session.endSession() when done.
  8. In applications, prefer the driver's withTransaction() helper, which retries on transient errors.

mongosh Examples

mongosh
// Setup: two accounts
use bank
db.accounts.insertMany([
  { _id: "A", balance: 500 },
  { _id: "B", balance: 100 }
])

// Transfer 200 from A to B atomically
const session = db.getMongo().startSession()
const accounts = session.getDatabase("bank").accounts

session.startTransaction({
  readConcern: { level: "snapshot" },
  writeConcern: { w: "majority" }
})

try {
  accounts.updateOne({ _id: "A" }, { $inc: { balance: -200 } })
  accounts.updateOne({ _id: "B" }, { $inc: { balance: 200 } })
  session.commitTransaction()
} catch (e) {
  session.abortTransaction()
  throw e
} finally {
  session.endSession()
}

Edge Cases & Pitfalls

Not available on standalone servers

Starting a transaction on a standalone mongod fails. Use a replica set, even a single-node one.

Using the wrong handle

Operations using db.accounts instead of the session's handle run outside the transaction.

Long transactions hurt

Holding a transaction open increases memory use and the chance of write conflicts. Keep it short.

Write conflicts

Concurrent transactions modifying the same document can abort with a TransientTransactionError. Retry the transaction.

Some operations are not allowed

Some operations have restrictions inside transactions, and what is allowed (for example creating collections or indexes) has changed between versions. Check the docs for your server version.

Cheat Sheet

TopicDetail
RequirementA replica set or sharded cluster; a standalone mongod does not support transactions
session = db.getMongo().startSession()Create a client session in mongosh
session.startTransaction()Begin a transaction in that session
session.commitTransaction()Make all changes durable and visible
session.abortTransaction()Discard all changes
session.endSession()Release session resources
session.withTransaction(fn)Helper in drivers that handles commit and retries transient errors
Pass the sessionEvery operation inside must use the session's collection handle
OptionsreadConcern, writeConcern, and readPreference can be set when starting a transaction
Time limitTransactions have a default lifetime limit of 60 seconds

Key Takeaways

Good data modeling often removes the need for transactions, because related data embedded in one document is already atomic. Use transactions for the cases that truly cross documents, and keep them short.

Frequently Asked Questions

Does MongoDB support ACID transactions?

Yes. Single-document operations are always atomic, and multi-document ACID transactions are supported on replica sets and sharded clusters.

Can I use transactions on a standalone server?

No. Transactions need a replica set or sharded cluster. You can convert a standalone to a single-node replica set for development.

When do I need a transaction?

When several documents must change together or not at all. If related data can be embedded in one document, a single-document write is already atomic.

What is a session?

A client session tracks a logical series of operations, and transactions run inside one.

What happens if my transaction fails?

Call abortTransaction() and nothing is applied. For transient errors, retry; drivers' withTransaction() helper does this automatically.

Are transactions slow?

They cost more than single writes because of coordination and snapshotting, so use them only where needed and keep them brief.

Next: MongoDB Read Preference

Continue the MongoDB learning path.

MongoDB Read Preference →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful