0
0
MongoDBquery~5 mins

Transactions vs atomic document writes in MongoDB

Choose your learning style9 modes available
Introduction
Transactions and atomic document writes help keep your data safe and correct when many changes happen at once.
When you need to update multiple documents and want all changes to succeed or fail together.
When you update only one document and want to make sure the change is complete and safe.
When you want to avoid partial updates that can cause wrong or broken data.
When you want to keep your data consistent even if something goes wrong during updates.
Syntax
MongoDB
/* Atomic document write example */
db.collection.updateOne({ _id: 1 }, { $set: { field: 'value' } })

/* Transaction example */
const session = client.startSession();
await session.withTransaction(async () => {
  await db.collection1.updateOne({ _id: 1 }, { $set: { field: 'value1' } }, { session });
  await db.collection2.updateOne({ _id: 2 }, { $set: { field: 'value2' } }, { session });
});
Atomic document writes affect only one document and are always all-or-nothing.
Transactions can include multiple operations on many documents or collections and commit all changes together.
Examples
This updates the name field in one user document atomically.
MongoDB
db.users.updateOne({ _id: 123 }, { $set: { name: 'Alice' } })
This transaction updates an order and inventory together. Both changes succeed or both fail.
MongoDB
const session = client.startSession();
await session.withTransaction(async () => {
  await db.orders.updateOne({ _id: 1 }, { $set: { status: 'shipped' } }, { session });
  await db.inventory.updateOne({ _id: 10 }, { $inc: { stock: -1 } }, { session });
});
Sample Program
This example transfers 100 units from account A to account B using a transaction to keep data safe.
MongoDB
const session = client.startSession();
try {
  session.startTransaction();
  await db.accounts.updateOne({ _id: 'A' }, { $inc: { balance: -100 } }, { session });
  await db.accounts.updateOne({ _id: 'B' }, { $inc: { balance: 100 } }, { session });
  await session.commitTransaction();
  console.log('Transaction committed');
} catch (error) {
  await session.abortTransaction();
  console.log('Transaction aborted');
} finally {
  session.endSession();
}
OutputSuccess
Important Notes
Atomic writes are simpler and faster but only work on single documents.
Transactions are more powerful but can be slower and need more setup.
Use transactions when you must update multiple documents together to keep data correct.
Summary
Atomic document writes update one document completely or not at all.
Transactions group many operations so they all succeed or fail together.
Choose atomic writes for simple single-document changes and transactions for complex multi-document updates.