What is ACID in MongoDB: Explanation and Examples
ACID refers to a set of properties that guarantee reliable transactions: Atomicity, Consistency, Isolation, and Durability. MongoDB supports multi-document ACID transactions to ensure data integrity during complex operations.How It Works
Think of ACID like a promise that your database makes to keep your data safe and correct, even if something goes wrong. Atomicity means that a group of operations either all happen or none happen, like flipping a light switch fully on or off, never halfway. Consistency ensures the database rules are always followed, so data stays valid.
Isolation means transactions don’t interfere with each other, like people working in separate rooms without disturbing one another. Durability guarantees that once a transaction finishes, its changes are saved permanently, even if the power goes out.
MongoDB uses these principles in its multi-document transactions, which let you update several documents safely as one unit, similar to how a bank ensures money moves correctly between accounts.
Example
This example shows a MongoDB transaction that transfers money between two accounts, ensuring both updates happen together or not at all.
const session = client.startSession(); try { session.startTransaction(); const accounts = client.db('bank').collection('accounts'); await accounts.updateOne({ accountId: 1 }, { $inc: { balance: -100 } }, { session }); await accounts.updateOne({ accountId: 2 }, { $inc: { balance: 100 } }, { session }); await session.commitTransaction(); console.log('Transaction committed successfully'); } catch (error) { await session.abortTransaction(); console.log('Transaction aborted due to error:', error); } finally { session.endSession(); }
When to Use
Use ACID transactions in MongoDB when you need to make multiple changes that must all succeed together to keep data accurate. For example, transferring money between bank accounts, updating inventory and orders simultaneously, or any case where partial updates could cause errors.
MongoDB’s ACID support is helpful in financial apps, e-commerce, and systems where data correctness is critical. For simple single-document updates, transactions are not needed because MongoDB already ensures atomicity at that level.
Key Points
- ACID stands for Atomicity, Consistency, Isolation, Durability.
- MongoDB supports multi-document ACID transactions starting from version 4.0.
- Transactions ensure all-or-nothing updates across multiple documents.
- Use transactions when data integrity across multiple documents is essential.
- Single-document operations in MongoDB are atomic by default.