Sessions and transactions help you group multiple database actions so they happen together or not at all. This keeps your data safe and correct.
Session and transaction syntax in MongoDB
Introduction
Syntax
MongoDB
const session = client.startSession(); session.startTransaction(); try { // database operations here await session.commitTransaction(); } catch (error) { await session.abortTransaction(); } finally { session.endSession(); }
Use
startSession() to begin a session.Wrap your operations between
startTransaction() and commitTransaction() or abortTransaction().Examples
MongoDB
const session = client.startSession(); session.startTransaction(); await collection.insertOne({name: 'Alice'}, {session}); await session.commitTransaction(); session.endSession();
MongoDB
const session = client.startSession(); try { session.startTransaction(); await collection.updateOne({name: 'Alice'}, {$set: {age: 30}}, {session}); await collection.updateOne({name: 'Bob'}, {$set: {age: 25}}, {session}); await session.commitTransaction(); } catch (e) { await session.abortTransaction(); } finally { session.endSession(); }
Sample Program
This program starts a session and transaction, inserts a user, updates the user's age, then commits the transaction. If any step fails, it aborts the transaction.
MongoDB
async function runTransaction(client) { const session = client.startSession(); try { session.startTransaction(); const coll = client.db('testdb').collection('users'); await coll.insertOne({name: 'John', age: 28}, {session}); await coll.updateOne({name: 'John'}, {$set: {age: 29}}, {session}); await session.commitTransaction(); console.log('Transaction committed'); } catch (error) { await session.abortTransaction(); console.log('Transaction aborted'); } finally { session.endSession(); } } // Assume client is connected MongoClient runTransaction(client);
Important Notes
Always end your session with endSession() to free resources.
Transactions only work on replica sets or sharded clusters, not standalone servers.
Pass the session object to all operations inside the transaction.
Summary
Sessions group operations for transactions.
Transactions ensure all-or-nothing execution.
Use startSession(), startTransaction(), commitTransaction(), and abortTransaction() properly.
Practice
1. What is the main purpose of using
startSession() in MongoDB?easy
Solution
Step 1: Understand the role of sessions
Sessions in MongoDB group multiple operations so they can be executed as a single unit.Step 2: Identify what
This method starts a new session to enable transactions or grouped operations.startSession()doesFinal Answer:
To begin a session that groups operations for transactions -> Option BQuick Check:
startSession() starts a session [OK]
Hint: Sessions group operations; startSession() begins it [OK]
Common Mistakes:
- Confusing startSession() with commitTransaction()
- Thinking startSession() commits or aborts transactions
- Assuming startSession() creates a database
2. Which of the following is the correct syntax to start a transaction in a MongoDB session named
session?easy
Solution
Step 1: Recall the MongoDB transaction method
The correct method to start a transaction on a session object isstartTransaction().Step 2: Check each option's syntax
Onlysession.startTransaction()matches the official MongoDB API.Final Answer:
session.startTransaction() -> Option CQuick Check:
startTransaction() starts transactions [OK]
Hint: Use startTransaction() to begin transactions on sessions [OK]
Common Mistakes:
- Using beginTransaction() which is not a MongoDB method
- Mixing method names like transactionStart()
- Using openTransaction() which does not exist
3. Given the following code snippet, what will be the output if the transaction commits successfully?
const session = client.startSession();
session.startTransaction();
await collection.insertOne({name: 'Alice'}, {session});
await session.commitTransaction();
session.endSession();
console.log('Transaction complete');medium
Solution
Step 1: Analyze the transaction flow
The code starts a session, begins a transaction, inserts a document, commits the transaction, and ends the session.Step 2: Determine the output after commit
Since commitTransaction() is awaited and no errors occur, the console.log will print 'Transaction complete'.Final Answer:
Transaction complete -> Option DQuick Check:
Successful commit logs 'Transaction complete' [OK]
Hint: commitTransaction() success leads to 'Transaction complete' log [OK]
Common Mistakes:
- Assuming commitTransaction() throws error without cause
- Thinking session.endSession() prevents console.log
- Confusing commitTransaction() with abortTransaction()
4. Identify the error in the following MongoDB transaction code:
const session = client.startSession();
session.startTransaction();
await collection.insertOne({item: 'book'});
await session.commitTransaction();
session.endSession();medium
Solution
Step 1: Review transaction usage in operations
Operations inside a transaction must include the session option to be part of it.Step 2: Check the insertOne call
The insertOne call lacks the {session} option, so it is not part of the transaction.Final Answer:
Missing session option in insertOne operation -> Option AQuick Check:
Operations need {session} to join transaction [OK]
Hint: Include {session} in operations inside transactions [OK]
Common Mistakes:
- Calling startSession() after startTransaction()
- Calling commitTransaction() before operations
- Ending session before committing transaction
5. You want to ensure that either all writes in a batch succeed or none do in MongoDB. Which sequence of commands correctly implements this using sessions and transactions?
hard
Solution
Step 1: Understand transaction requirements
All operations must be inside a started transaction and include the session option.Step 2: Evaluate each option
const session = client.startSession(); session.startTransaction(); await collection.insertOne(doc1, {session}); await collection.insertOne(doc2, {session}); await session.commitTransaction(); session.endSession(); correctly starts a session, starts a transaction, performs writes with session, commits, and ends session. Others either miss session in operations, start transaction late, or abort instead of commit.Final Answer:
const session = client.startSession(); session.startTransaction(); await collection.insertOne(doc1, {session}); await collection.insertOne(doc2, {session}); await session.commitTransaction(); session.endSession(); -> Option AQuick Check:
Start session, startTransaction, ops with session, commit, endSession [OK]
Hint: Start session, startTransaction, ops with session, commit, endSession [OK]
Common Mistakes:
- Not passing {session} in operations
- Starting transaction after operations
- Aborting instead of committing for success
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
