Commit and abort control if changes to the database are saved or canceled. This helps keep data correct and safe.
Commit and abort behavior in MongoDB
Introduction
Syntax
MongoDB
const session = client.startSession(); await session.startTransaction(); try { // database operations await session.commitTransaction(); } catch (error) { await session.abortTransaction(); } finally { session.endSession(); }
Use startTransaction() to begin a transaction.
Use commitTransaction() to save changes.
Use abortTransaction() to cancel changes.
Examples
MongoDB
const session = client.startSession(); await session.startTransaction(); try { await collection.insertOne({name: 'Alice'}, {session}); await session.commitTransaction(); } catch (e) { await session.abortTransaction(); } finally { session.endSession(); }
MongoDB
const session = client.startSession(); await session.startTransaction(); try { await collection.updateOne({name: 'Bob'}, {$set: {age: 30}}, {session}); await collection.deleteOne({name: 'Charlie'}, {session}); await session.commitTransaction(); } catch (e) { await session.abortTransaction(); } finally { session.endSession(); }
Sample Program
This program starts a transaction, inserts a user, updates the user, and commits the changes. If any step fails, it aborts the transaction.
MongoDB
const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('testdb'); const collection = db.collection('users'); const session = client.startSession(); await session.startTransaction(); try { await collection.insertOne({name: 'Diana'}, {session}); await collection.updateOne({name: 'Diana'}, {$set: {age: 25}}, {session}); await session.commitTransaction(); console.log('Transaction committed'); } catch (error) { await session.abortTransaction(); console.log('Transaction aborted'); } finally { session.endSession(); await client.close(); } } run();
Important Notes
Transactions work only on replica sets or sharded clusters in MongoDB.
Always end the session with endSession() to free resources.
Use transactions to keep multiple operations safe and consistent.
Summary
Commit saves all changes made in a transaction.
Abort cancels all changes made in a transaction.
Use transactions to group multiple operations safely.
Practice
1. What happens when you
commit a transaction in MongoDB?easy
Solution
Step 1: Understand commit behavior
Committing a transaction means saving all changes made during that transaction permanently to the database.Step 2: Compare with abort
Unlike abort, which cancels changes, commit finalizes them.Final Answer:
All changes made during the transaction are saved permanently. -> Option AQuick Check:
Commit = Save changes [OK]
Hint: Commit means save all changes made in the transaction [OK]
Common Mistakes:
- Confusing commit with abort
- Thinking commit only saves some changes
- Believing commit pauses the transaction
2. Which of the following is the correct syntax to abort a transaction in MongoDB using the shell?
easy
Solution
Step 1: Recall MongoDB transaction abort syntax
The correct method to abort a transaction issession.abortTransaction().Step 2: Eliminate incorrect options
session.commit()is invalid,db.abort()andtransaction.abort()are not valid MongoDB shell commands.Final Answer:
session.abortTransaction() -> Option BQuick Check:
Abort transaction = session.abortTransaction() [OK]
Hint: Abort transaction uses session.abortTransaction() method [OK]
Common Mistakes:
- Using commit() instead of abortTransaction()
- Trying to abort with db.abort() which doesn't exist
- Confusing transaction object with session
3. Consider this MongoDB transaction code snippet:
const session = client.startSession();
session.startTransaction();
await collection.insertOne({name: 'Alice'}, {session});
await session.abortTransaction();
const count = await collection.countDocuments({name: 'Alice'});
console.log(count);
What will be printed?medium
Solution
Step 1: Analyze transaction operations
The document insertion happens inside a transaction that is aborted immediately after.Step 2: Understand abort effect on data
Aborting the transaction cancels the insert, so the document is not saved.Final Answer:
0 -> Option AQuick Check:
Abort cancels insert, count = 0 [OK]
Hint: Aborted inserts do not persist, count remains zero [OK]
Common Mistakes:
- Assuming insert stays after abort
- Expecting count to be 1
- Thinking abort throws error
4. You wrote this MongoDB transaction code but it throws an error:
const session = client.startSession();
session.startTransaction();
await collection.insertOne({item: 'book'}, {session});
session.commitTransaction();
session.endSession();
What is the likely cause of the error?medium
Solution
Step 1: Check async calls in transaction
commitTransaction() returns a promise and must be awaited to complete properly.Step 2: Identify missing await causes error
Without await, the code may proceed before commit finishes, causing errors.Final Answer:
Missing await before commitTransaction() -> Option CQuick Check:
Async commit needs await [OK]
Hint: Always await commitTransaction() to avoid errors [OK]
Common Mistakes:
- Not awaiting commitTransaction()
- Calling startTransaction() multiple times
- Calling endSession() too early
5. You want to update two documents atomically in MongoDB. You start a transaction, update the first document, then update the second. If the second update fails, what should you do to ensure no partial changes remain?
hard
Solution
Step 1: Understand atomicity in transactions
Transactions ensure all-or-nothing changes. If one update fails, the whole transaction should be canceled.Step 2: Apply abort to cancel partial changes
Aborting the transaction cancels all changes, preventing partial updates.Final Answer:
Abort the transaction to cancel all changes. -> Option DQuick Check:
Fail in transaction = abort all changes [OK]
Hint: Abort transaction to avoid partial updates on failure [OK]
Common Mistakes:
- Committing partial updates
- Trying to manually fix partial changes
- Ignoring failure and continuing
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
