What is a transaction in MongoDB?
A transaction in MongoDB is a group of operations that run as a single unit, guaranteeing that either all the operations apply, or none of them do. That means the data stays in a consistent state, even if something goes wrong.
The core idea
A transaction is needed when preserving the atomicity of actions matters. For example: updating two documents in different collections and being sure it never happens that one gets updated while the other doesn't.
What a transaction guarantees
- Atomicity, all or nothing
- Consistency of the data
- Isolation of the changes
- Durability, the write won't be lost after commit
Where it's used
- banking operations
- complex updates across different collections
- operations that need to stay strictly in sync
Summary
A transaction in MongoDB is a way to run several operations on data as a single indivisible operation, ensuring data integrity and stability.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.