Transactions
Transactions in MongoDB allow multiple read and write operations to be executed atomically on a single document or multiple documents. In simpler terms, a transaction treats a set of changes to the database as a single unit, ensuring data integrity and consistency. If any part of the transaction fails, all changes within that transaction are rolled back, leaving the data in its original state.
Understanding Transactions
Using transactions in MongoDB is similar to how transactions are used in relational databases. They provide a mechanism to isolate an operation or a sequence of operations, so that other operations can't interfere with them. A transaction, once committed to the database, is saved permanently.
There are two types of transactions in MongoDB:
Single Document Transactions: As the name suggests, these transactions only affect a single document. They are available in all versions of MongoDB and are used by default when you update a document.
Multi-Document Transactions: Introduced in MongoDB 4.0, these transactions can affect multiple documents within a single transaction. This can be extremely useful when you need to ensure that multiple operations succeed or fail as a unit.
How to Use Transactions
Before you start with transactions in MongoDB, you need to start a session using the startSession()
method.
var mySession = db.getMongo().startSession();
After you start a session, you can then start a transaction with the startTransaction()
method.
mySession.startTransaction();
Within the transaction, you can perform your read and write operations. Once you're done with your operations, you can commit the transaction with the commitTransaction()
method.
mySession.commitTransaction();
If something goes wrong and you need to abort the transaction, you can do so with the abortTransaction()
method.
mySession.abortTransaction();
Finally, once you're done with the session, you can end it with the endSession()
method.
mySession.endSession();
Working with Multi-Document Transactions
Working with multi-document transactions is similar to working with single document transactions. The only difference is that you can perform operations on multiple documents.
Here's an example of a multi-document transaction:
var mySession = db.getMongo().startSession();
mySession.startTransaction();
var booksCollection = mySession.getDatabase('library').getCollection('books');
var usersCollection = mySession.getDatabase('library').getCollection('users');
try {
booksCollection.updateOne({ title: 'Moby Dick' }, { $inc: { quantity: -1 } });
usersCollection.updateOne({ name: 'John Doe' }, { $push: { borrowedBooks: 'Moby Dick' } });
mySession.commitTransaction();
} catch (error) {
mySession.abortTransaction();
console.log('Transaction aborted due to error: ', error);
} finally {
mySession.endSession();
}
In the above example, we start a transaction and perform two operations: decreasing the quantity of a book and adding that book to a user's list of borrowed books. If any of these operations fail, the transaction is aborted and no changes are made to the database.
Conclusion
Transactions in MongoDB provide a powerful tool for ensuring data consistency and integrity. Whether you're working with a single document or multiple documents, transactions allow you to group operations together and ensure they all succeed or fail as a unit. This is a crucial aspect of working with any database system. Happy learning!