Welcome back to CodeYourCraft! Today, we're diving into MongoDB Transactions, a powerful feature that helps keep your database consistent and reliable. Let's get started! 🎉
A transaction is a series of operations that are executed together and must either complete entirely or not at all. Transactions are crucial for maintaining data integrity, especially when dealing with multiple operations that affect the same data.
MongoDB supports transactions through a feature called Multi-Document Acquisition (MDA), which allows you to perform multiple read and write operations atomically on a single collection.
Before we dive into transactions, let's create a simple collection.
db.createCollection("inventory");Now, let's insert some documents into our inventory collection.
db.inventory.insertMany([
{ item: "Journal", qty: 25, tags: ["leather"] },
{ item: "Notebook", qty: 50, tags: ["lines", "wideRule"] },
{ item: "Pen", qty: 75, tags: ["ballpoint"] }
]);In MongoDB, transactions are useful when you want to perform multiple operations that affect the same data and need to ensure data consistency. Let's take an example where we want to decrease the quantity of an item and update its tags simultaneously.
To start a transaction, we use the startTransaction() method.
db.inventory.startTransaction();Now, we can perform multiple operations on our inventory collection within the transaction.
// Get the document we want to update
var journal = db.inventory.findOne({ item: "Journal" });
// Decrease the quantity and update the tags
db.inventory.updateOne(
{ _id: journal._id },
{
$set: {
qty: journal.qty - 1,
tags: journal.tags.concat(["sold"])
}
}
);If both operations are successful, we can commit the transaction.
db.inventory.commitTransaction();If an error occurs during the transaction, MongoDB will automatically rollback the transaction.
db.inventory.abortTransaction();What is a transaction in MongoDB?
How does MongoDB support transactions?
That's it for today! Transactions are a powerful tool to maintain data consistency in MongoDB. Stay tuned for more tutorials on CodeYourCraft. Happy coding! 🚀