MongoDB Transactions
MongoDB transactions let several operations across multiple documents or collections succeed or fail together. Single-document writes are always atomic in MongoDB, so you only need a transaction when one business action touches more than one document.
Transactions require a replica set or sharded cluster (Atlas clusters are replica sets).
A Transaction in mongosh
Start a session, start a transaction, use the session's database handle, then commit or abort.
const session = db.getMongo().startSession()
const shop = session.getDatabase("shop")
session.startTransaction()
try {
shop.orders.insertOne({ orderNo: 111, product: "Olive Oil", qty: 5 })
shop.products.updateOne({ name: "Olive Oil" }, { $inc: { stock: -5 } })
session.commitTransaction()
print("committed")
} catch (e) {
session.abortTransaction()
print("aborted: " + e.message)
} finally {
session.endSession()
}committed
withTransaction in Node.js
Drivers offer withTransaction, which also retries on transient errors automatically.
await session.withTransaction(async () => {
await orders.insertOne({ orderNo: 112, qty: 2 }, { session })
await products.updateOne({ name: "Honey" }, { $inc: { stock: -2 } }, { session })
})
console.log('done')done
Best Practices
- Prefer schema designs where one document holds the data that must change together
- Keep transactions short; the default time limit is 60 seconds
- Pass the session to every operation inside the transaction
- Handle TransientTransactionError by retrying
Frequently asked questions
Does MongoDB support ACID transactions?
Yes. Since 4.0 for replica sets and 4.2 for sharded clusters, MongoDB supports multi-document ACID transactions.
Why do I get "Transaction numbers are only allowed on a replica set"?
Your server runs standalone. Start it as a single-node replica set (--replSet rs0 then rs.initiate()) or use Atlas.
Are MongoDB transactions slow?
They add overhead compared to single-document writes, so use them only when needed. For most operations a well-designed document makes them unnecessary.