What if your important data changes halfway and leaves your system broken? Transactions are the safety net you need.
Why transactions are needed in MongoDB - The Real Reasons
Imagine you are updating a bank account balance and the transaction history manually by editing multiple documents one by one in MongoDB.
If something goes wrong halfway, like a power cut or a mistake, your data will be inconsistent.
Manually updating multiple related documents is slow and risky.
You might forget to update one part or end up with partial changes, causing errors and confusion.
Transactions let you group multiple operations into one unit.
Either all changes happen together, or none happen at all, keeping your data safe and consistent.
db.accounts.updateOne({id:1}, {$inc: {balance: -100}})
db.transactions.insertOne({accountId:1, amount:-100})const session = client.startSession();
session.withTransaction(() => {
db.accounts.updateOne({id:1}, {$inc: {balance: -100}}, {session});
db.transactions.insertOne({accountId:1, amount:-100}, {session});
});
session.endSession();Transactions enable safe, reliable updates across multiple documents, ensuring your data stays correct even if something unexpected happens.
When transferring money between two bank accounts, transactions ensure that the amount is deducted from one account and added to the other together, preventing money loss or duplication.
Manual updates across documents can cause inconsistent data.
Transactions group operations to succeed or fail as one.
This keeps your database accurate and trustworthy.