A session in MongoDB is a context for performing operations that can be grouped together, such as transactions. It helps track and manage these operations consistently.
Click to reveal answer
beginner
How do you start a transaction in MongoDB using a session?
You start a transaction by calling session.startTransaction() after starting a session with client.startSession().
Click to reveal answer
beginner
What is the purpose of commitTransaction() in MongoDB?
The commitTransaction() method finalizes the transaction, making all changes permanent in the database.
Click to reveal answer
beginner
How do you abort a transaction in MongoDB?
You abort a transaction by calling session.abortTransaction(). This cancels all changes made during the transaction.
Click to reveal answer
intermediate
Show the basic syntax to run a transaction in MongoDB using a session.
B. startSession() should be called after startTransaction()
C. commitTransaction() should be called before insertOne
D. endSession() should be called before commitTransaction()
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 A
Quick 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?
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.