MongoDB Transactions
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
| Reason | Benefit |
|---|---|
| All-or-nothing changes | Moving money between accounts either updates both balances or neither. |
| Consistent reads | Reads inside a transaction see a consistent snapshot of the data. |
| Familiar semantics | ACID behavior matches what developers expect from relational databases. |
| Works across collections | A transaction can touch many collections in the same replica set. |
How To Use It
- Run mongosh against a replica set, such as an Atlas cluster or a local one started with --replSet.
- Create a session with db.getMongo().startSession().
- Get collection handles from the session: session.getDatabase("bank").accounts.
- Call session.startTransaction() with the options you need.
- Perform the related writes using the session's handles.
- Call commitTransaction() when all succeed, or abortTransaction() on any error.
- Call session.endSession() when done.
- In applications, prefer the driver's withTransaction() helper, which retries on transient errors.
mongosh Examples
// 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
| Topic | Detail |
|---|---|
| Requirement | A 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 session | Every operation inside must use the session's collection handle |
| Options | readConcern, writeConcern, and readPreference can be set when starting a transaction |
| Time limit | Transactions 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.
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.
8 people found this page helpful
