Assignments Of Day 17: MongoDB Transactions
Assignment 1: MongoDB Transaction to Insert Documents into Multiple Collections
Objective:
Create a MongoDB transaction that inserts documents into the students and courses collections. If the insertion into one collection fails, the transaction should be rolled back.
Solution:
javascriptconst { MongoClient } = require('mongodb'); async function runTransaction() { const client = new MongoClient('mongodb://localhost:27017'); const session = client.startSession(); try { session.startTransaction(); const studentsCollection = client.db('school').collection('students'); const coursesCollection = client.db('school').collection('courses'); // Insert a student document into the "students" collection await studentsCollection.insertOne( { name: "John Doe", age: 22, major: "Computer Science" }, { session } ); // Insert a course document into the "courses" collection await coursesCollection.insertOne( { courseName: "MongoDB 101", instructor: "Dr. Smith", credits: 3 }, { session } ); // Commit the transaction if both operations succeed await session.commitTransaction(); console.log("Transaction committed successfully"); } catch (error) { // If an error occurs, abort the transaction and rollback all changes console.log("Transaction aborted due to an error:", error); await session.abortTransaction(); } finally { session.endSession(); client.close(); }} runTransaction();Explanation:
1. A session is started using startSession().
2. A transaction is started with startTransaction().
3. Documents are inserted into the students and courses collections.
4. The transaction is committed if both insertions succeed, otherwise, it is aborted.
5. The session is ended, and the database connection is closed.
Assignment 2: MongoDB Transaction to Update Multiple Documents
Objective:
Implement a MongoDB transaction to update multiple documents in the students collection, ensuring that all updates are committed or rolled back together.
Solution:
javascriptconst { MongoClient } = require('mongodb'); async function updateStudentsTransaction() { const client = new MongoClient('mongodb://localhost:27017'); const session = client.startSession(); try { session.startTransaction(); const studentsCollection = client.db('school').collection('students'); // Update student documents await studentsCollection.updateOne( { name: "John Doe" }, { $set: { age: 23 } }, { session } ); await studentsCollection.updateOne( { name: "Jane Doe" }, { $set: { major: "Mathematics" } }, { session } ); // Commit the transaction if both updates are successful await session.commitTransaction(); console.log("Transaction committed successfully"); } catch (error) { // If any update operation fails, abort the transaction console.log("Transaction aborted due to an error:", error); await session.abortTransaction(); } finally { session.endSession(); client.close(); }} updateStudentsTransaction();Explanation:
- The transaction begins, and the two
updateOneoperations are performed in the same session. - Both updates are successful if no errors occur, and the transaction is committed.
- If any error occurs, the transaction is rolled back using
abortTransaction().
Assignment 3: MongoDB Transaction with Error Handling and Rollback
Objective:
Create a MongoDB transaction that inserts documents into students and courses, with error handling to ensure the transaction is rolled back on failure.
Solution:
javascriptconst { MongoClient } = require('mongodb'); async function runTransactionWithErrorHandling() { const client = new MongoClient('mongodb://localhost:27017'); const session = client.startSession(); try { session.startTransaction(); const studentsCollection = client.db('school').collection('students'); const coursesCollection = client.db('school').collection('courses'); // Insert student document await studentsCollection.insertOne( { name: "Alice", age: 21, major: "Physics" }, { session } ); // Insert course document await coursesCollection.insertOne( { courseName: "Database Systems", instructor: "Dr. Johnson", credits: 4 }, { session } ); // Simulate an error (e.g., insertion failure) throw new Error("Simulated Error: Rollback Transaction"); await session.commitTransaction(); console.log("Transaction committed successfully"); } catch (error) { console.log("Error encountered:", error); await session.abortTransaction(); } finally { session.endSession(); client.close(); }} runTransactionWithErrorHandling();Explanation:
- After inserting documents into both collections, we simulate an error to demonstrate how the transaction can be rolled back.
- The error causes the
abortTransaction()to be called.
Assignment 4: Implement Transaction for Deleting Documents from Multiple Collections
Objective:
Create a MongoDB transaction that deletes documents from the students and courses collections. If one deletion fails, the transaction should be rolled back.
Solution:
javascriptconst { MongoClient } = require('mongodb'); async function deleteDocumentsTransaction() { const client = new MongoClient('mongodb://localhost:27017'); const session = client.startSession(); try { session.startTransaction(); const studentsCollection = client.db('school').collection('students'); const coursesCollection = client.db('school').collection('courses'); // Delete a student document await studentsCollection.deleteOne( { name: "Alice" }, { session } ); // Delete a course document await coursesCollection.deleteOne( { courseName: "MongoDB 101" }, { session } ); // Commit the transaction if both deletions succeed await session.commitTransaction(); console.log("Transaction committed successfully"); } catch (error) { console.log("Transaction aborted due to an error:", error); await session.abortTransaction(); } finally { session.endSession(); client.close(); }} deleteDocumentsTransaction();Explanation:
- The transaction starts with the deletion of documents from two collections.
- If either deletion fails, the transaction is aborted, and the changes are rolled back.
Assignment 5: MongoDB Transaction to Transfer Money Between Accounts
Objective:
Create a MongoDB transaction that transfers money from one account to another by updating documents in two collections (accounts and transactions).
Solution:
javascriptconst { MongoClient } = require('mongodb'); async function transferMoney() { const client = new MongoClient('mongodb://localhost:27017'); const session = client.startSession(); try { session.startTransaction(); const accountsCollection = client.db('bank').collection('accounts'); const transactionsCollection = client.db('bank').collection('transactions'); // Deduct from Account A await accountsCollection.updateOne( { accountNumber: "12345" }, { $inc: { balance: -500 } }, { session } ); // Add to Account B await accountsCollection.updateOne( { accountNumber: "67890" }, { $inc: { balance: 500 } }, { session } ); // Insert transaction record await transactionsCollection.insertOne( { fromAccount: "12345", toAccount: "67890", amount: 500, date: new Date() }, { session } ); // Commit the transaction if all operations succeed await session.commitTransaction(); console.log("Money transfer completed successfully"); } catch (error) { console.log("Transaction aborted due to an error:", error); await session.abortTransaction(); } finally { session.endSession(); client.close(); }} transferMoney();Explanation:
- A transaction is initiated to transfer money from one account to another.
- The balance is updated in both accounts, and a transaction record is inserted.
- If any operation fails, the transaction is rolled back.
Assignment 6: Implement Transaction to Add User and Post Simultaneously
Objective:
Create a MongoDB transaction to add a new user and their first post in the same transaction. If any operation fails, the transaction should be rolled back.
Solution:
javascriptconst { MongoClient } = require('mongodb'); async function addUserAndPost() { const client = new MongoClient('mongodb://localhost:27017'); const session = client.startSession(); try { session.startTransaction(); const usersCollection = client.db('blog').collection('users'); const postsCollection = client.db('blog').collection('posts'); // Add a new user await usersCollection.insertOne( { username: "johndoe", email: "john@example.com" }, { session } ); // Add a post by the new user await postsCollection.insertOne( { userId: "johndoe", title: "My First Post", content: "This is the content of my first post." }, { session } ); // Commit the transaction await session.commitTransaction(); console.log("User and post added successfully"); } catch (error) { console.log("Transaction aborted due to an error:", error); await session.abortTransaction(); } finally { session.endSession(); client.close(); }} addUserAndPost();Explanation:
- This transaction ensures that both the user and the post are added successfully.
- If one operation fails, the transaction is rolled back to prevent partial data.
Assignment 7: MongoDB Transaction to Handle Multiple Withdrawals
Objective:
Create a MongoDB transaction that processes multiple withdrawals from different accounts, ensuring that the transaction is atomic and any failure will roll back all withdrawals.
Solution:
javascriptconst { MongoClient } = require('mongodb'); async function processWithdrawals() { const client = new MongoClient('mongodb://localhost:27017'); const session = client.startSession(); try { session.startTransaction(); const accountsCollection = client.db('bank').collection('accounts'); // Process multiple withdrawals await accountsCollection.updateOne( { accountNumber: "12345" }, { $inc: { balance: -300 } }, { session } ); await accountsCollection.updateOne( { accountNumber: "67890" }, { $inc: { balance: -150 } }, { session }
);
// Simulate an error throw new Error("Simulated error during withdrawal");
await session.commitTransaction(); console.log("Withdrawals processed successfully"); } catch (error) { console.log("Transaction aborted due to an error:", error); await session.abortTransaction(); } finally { session.endSession(); client.close(); }
}
processWithdrawals();Explanation:
- Multiple withdrawal operations are attempted in a single transaction.
- If any operation fails (simulated here by an error), the entire transaction is rolled back, ensuring no partial changes.
Assignment 8: MongoDB Transaction for Bulk Update Operation
Objective:
Create a MongoDB transaction that updates the status field of multiple orders in a orders collection.
Solution:
javascript
const { MongoClient } = require('mongodb');
async function bulkUpdateOrders() { const client = new MongoClient('mongodb://localhost:27017'); const session = client.startSession();
try { session.startTransaction();
const ordersCollection = client.db('store').collection('orders');
// Bulk update orders await ordersCollection.updateMany( { status: "pending" }, { $set: { status: "shipped" } }, { session }
);
await session.commitTransaction(); console.log("Bulk update successful"); } catch (error) { console.log("Transaction aborted due to an error:", error); await session.abortTransaction(); } finally { session.endSession(); client.close(); }
}
bulkUpdateOrders();Explanation:
- The transaction updates all documents with a "pending" status to "shipped".
- If any update fails, the transaction will be rolled back.
Assignment 9: MongoDB Transaction for Combined Data Insertion
Objective:
Create a MongoDB transaction to insert data into two collections: customers and orders.
Solution:
javascript
const { MongoClient } = require('mongodb');
async function insertCustomerAndOrder() { const client = new MongoClient('mongodb://localhost:27017'); const session = client.startSession();
try { session.startTransaction();
const customersCollection = client.db('shop').collection('customers'); const ordersCollection = client.db('shop').collection('orders');
// Insert customer data await customersCollection.insertOne( { name: "Bob", email: "bob@example.com", address: "123 Main St" }, { session }
);
// Insert order data await ordersCollection.insertOne( { customerName: "Bob", product: "Laptop", quantity: 1 }, { session }
);
await session.commitTransaction(); console.log("Customer and order inserted successfully"); } catch (error) { console.log("Transaction aborted due to an error:", error); await session.abortTransaction(); } finally { session.endSession(); client.close(); }
}
insertCustomerAndOrder();Explanation:
- Both customer and order documents are inserted into the respective collections in a transaction.
- If any insertion fails, the transaction is rolled back.
Assignment 10: MongoDB Transaction for Data Consistency in Multi-Step Process
Objective:
Create a MongoDB transaction that ensures data consistency while performing multiple updates in a multi-step process.
Solution:
javascript
const { MongoClient } = require('mongodb');
async function processMultiStepOperation() { const client = new MongoClient('mongodb://localhost:27017'); const session = client.startSession();
try { session.startTransaction();
const ordersCollection = client.db('store').collection('orders'); const inventoryCollection = client.db('store').collection('inventory');
// Step 1: Update order status await ordersCollection.updateOne( { orderId: 1001 }, { $set: { status: "shipped" } }, { session }
);
// Step 2: Update inventory await inventoryCollection.updateOne( { productId: 1 }, { $inc: { stock: -1 } }, { session }
);
await session.commitTransaction(); console.log("Multi-step operation completed successfully"); } catch (error) { console.log("Transaction aborted due to an error:", error); await session.abortTransaction(); } finally { session.endSession(); client.close(); }
}
processMultiStepOperation();Explanation:
- The transaction handles multiple steps, such as updating an order status and inventory stock.
- If any step fails, the transaction ensures data consistency by rolling back all changes.
