MongoDB Transactions
Every write to a single document in MongoDB is atomic: either all of its changes are applied, or none. Because related data is often embedded in one document, that covers most needs. When a change must touch several documents (or collections) all-or-nothing, MongoDB offers multi-document ACID transactions, much like a relational database.
Single-document atomicity first
An update with several operators on one document is applied as a unit, and no other client can see it half-done:
db.orders.updateOne({ _id: 1019 }, {
$set: { status: 'shipped' },
$push: { items: { productId: 15, name: 'Paper Filters (100)', qty: 1, price: 6 } },
$inc: { total: 6 }
});
print(db.orders.findOne({ _id: 1019 }, { status: 1, total: 1, lines: { $size: '$items' } }));{ _id: 1019, status: 'shipped', total: 17.5, lines: 3 }
The status change, the new item and the new total arrive together. Before reaching for a transaction, ask whether a better document design would make the change a single-document write.
What can go wrong without a transaction
Moving stock between two warehouse documents needs two updates. If the program crashes between them, the data is inconsistent. This simulation "crashes" after the first update:
db.warehouses.insertMany([
{ _id: 'north', espressoBags: 30 },
{ _id: 'south', espressoBags: 10 }
]);
function transfer(qty, crashHalfway) {
db.warehouses.updateOne({ _id: 'north' }, { $inc: { espressoBags: -qty } });
if (crashHalfway) throw new Error('connection lost');
db.warehouses.updateOne({ _id: 'south' }, { $inc: { espressoBags: qty } });
}
try { transfer(5, true); } catch (err) { print('transfer failed:', err.message); }
const total = db.warehouses.aggregate([{ $group: { _id: null, bags: { $sum: '$espressoBags' } } }]).toArray()[0].bags;
print('bags in all warehouses:', total, '(should be 40)');transfer failed: connection lost
bags in all warehouses: 35 (should be 40)
Five bags vanished. A transaction would have rolled back the first update.
Transactions need a replica set
Transactions require a replica set or a sharded cluster. Atlas clusters, even the free tier, are replica sets, and a local mongod can be started as a one-member replica set (mongod --replSet rs0, then rs.initiate()). The server used to verify this course's examples is a standalone mongod, so the transaction code below is shown without a Run button. You can check what kind of server you are connected to:
const hello = db.hello();
print(hello.setName ? 'replica set ' + hello.setName : 'standalone server: transactions are not available');standalone server: transactions are not available
A transaction in mongosh
A transaction runs inside a session. Operations must use collection handles obtained through the session:
const session = db.getMongo().startSession();
const wh = session.getDatabase('shop').warehouses;
session.startTransaction({ readConcern: { level: 'snapshot' }, writeConcern: { w: 'majority' } });
try {
wh.updateOne({ _id: 'north', espressoBags: { $gte: 5 } }, { $inc: { espressoBags: -5 } });
wh.updateOne({ _id: 'south' }, { $inc: { espressoBags: 5 } });
session.commitTransaction(); // both changes become visible together
} catch (err) {
session.abortTransaction(); // neither change is kept
throw err;
} finally {
session.endSession();
}Until commitTransaction(), other clients don't see any of the changes. After abortTransaction(), it is as if nothing happened.
The callback API (recommended)
Transactions can fail with transient errors (for example a write conflict with another transaction) that should simply be retried. Drivers provide withTransaction, which commits, retries and aborts for you. In Node.js:
const session = client.startSession();
try {
await session.withTransaction(async () => {
const warehouses = client.db('shop').collection('warehouses');
await warehouses.updateOne({ _id: 'north' }, { $inc: { espressoBags: -5 } }, { session });
await warehouses.updateOne({ _id: 'south' }, { $inc: { espressoBags: 5 } }, { session });
});
} finally {
await session.endSession();
}Every operation inside must pass the session, otherwise it runs outside the transaction.
Good practice
| Do | Why |
|---|---|
| Keep transactions short (well under the default 60-second limit) | long transactions hold resources and conflict more |
| Touch few documents (≲ 1,000 modified) | large transactions are slow and use cache |
Use writeConcern: { w: 'majority' } |
the commit survives a primary failover |
Retry on TransientTransactionError |
the callback API does it for you |
| Prefer schema design over transactions | single-document writes are faster and simpler |
Test yourself
Which writes are atomic in MongoDB without a transaction?
- None
- Writes to a single document, even with several operators
- Any updateMany
- All writes in one script
What does a MongoDB deployment need for multi-document transactions?
- Nothing special
- A replica set or sharded cluster
- A text index
- Schema validation
Inside withTransaction, what happens if you forget { session } on an operation?
- It throws an error
- It runs outside the transaction and won't be rolled back
- It is ignored
- The transaction commits early