Bird
Raised Fist0
MongoDBquery~20 mins

Session and transaction syntax in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MongoDB Transaction Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
What is the output of this MongoDB transaction commit?
Consider the following MongoDB transaction code snippet. What will be the output after the transaction commits successfully?
MongoDB
const session = client.startSession();
let result;
try {
  session.startTransaction();
  const coll = client.db('shop').collection('orders');
  result = await coll.insertOne({item: 'book', qty: 3}, {session});
  await session.commitTransaction();
} catch (e) {
  await session.abortTransaction();
} finally {
  await session.endSession();
}
return result.insertedId;
AUndefined because session is not passed
Bnull
CThrows a SyntaxError
DObjectId of the inserted document
Attempts:
2 left
💡 Hint
Think about what insertOne returns when used inside a transaction with a session.
📝 Syntax
intermediate
1:30remaining
Which option correctly starts a MongoDB session and transaction?
Select the code snippet that correctly starts a session and a transaction in MongoDB.
Aconst session = client.startSession(); session.begin();
Bconst session = client.startSession(); session.startTransaction();
Cconst session = client.sessionStart(); session.beginTransaction();
Dconst session = client.newSession(); session.startTransaction();
Attempts:
2 left
💡 Hint
Check the official MongoDB Node.js driver method names for sessions and transactions.
🔧 Debug
advanced
2:30remaining
Why does this MongoDB transaction code throw an error?
Given the code below, why does it throw an error when trying to commit the transaction? const session = client.startSession(); session.startTransaction(); const coll = client.db('test').collection('users'); await coll.insertOne({name: 'Alice'}); await session.commitTransaction(); session.endSession();
AThe insertOne operation is missing the session option, so it is outside the transaction
BcommitTransaction must be called before startTransaction
Csession.endSession() must be awaited
DTransactions are not supported on the 'test' database
Attempts:
2 left
💡 Hint
Think about how MongoDB knows which operations belong to the transaction.
❓ optimization
advanced
2:00remaining
How to optimize MongoDB transaction usage for multiple writes?
You want to perform multiple write operations inside a MongoDB transaction efficiently. Which approach is best?
AStart a session and transaction once, perform all writes with the session option, then commit once
BStart and commit a transaction for each write operation separately
CPerform writes without a transaction to avoid overhead
DUse multiple sessions, one per write, and commit each separately
Attempts:
2 left
💡 Hint
Think about minimizing transaction overhead and ensuring atomicity.
🧠 Conceptual
expert
3:00remaining
What happens if a MongoDB transaction exceeds the maximum allowed duration?
In MongoDB, if a transaction runs longer than the configured maximum transaction lifetime, what is the expected behavior?
AThe transaction pauses until manually resumed
BThe transaction commits automatically regardless of duration
CThe transaction is automatically aborted by the server
DThe transaction continues indefinitely without interruption
Attempts:
2 left
💡 Hint
Consider MongoDB's safeguards to prevent long-running transactions.

Practice

(1/5)
1. What is the main purpose of using startSession() in MongoDB?
easy
A. To commit changes to the database
B. To begin a session that groups operations for transactions
C. To abort a running transaction
D. To create a new database

Solution

  1. Step 1: Understand the role of sessions

    Sessions in MongoDB group multiple operations so they can be executed as a single unit.
  2. Step 2: Identify what startSession() does

    This method starts a new session to enable transactions or grouped operations.
  3. Final Answer:

    To begin a session that groups operations for transactions -> Option B
  4. Quick 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
A. session.beginTransaction()
B. session.transactionStart()
C. session.startTransaction()
D. session.openTransaction()

Solution

  1. Step 1: Recall the MongoDB transaction method

    The correct method to start a transaction on a session object is startTransaction().
  2. Step 2: Check each option's syntax

    Only session.startTransaction() matches the official MongoDB API.
  3. Final Answer:

    session.startTransaction() -> Option C
  4. Quick 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
A. No output
B. Transaction aborted
C. SyntaxError
D. Transaction complete

Solution

  1. Step 1: Analyze the transaction flow

    The code starts a session, begins a transaction, inserts a document, commits the transaction, and ends the session.
  2. Step 2: Determine the output after commit

    Since commitTransaction() is awaited and no errors occur, the console.log will print 'Transaction complete'.
  3. Final Answer:

    Transaction complete -> Option D
  4. Quick 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
A. Missing session option in insertOne operation
B. startSession() should be called after startTransaction()
C. commitTransaction() should be called before insertOne
D. endSession() should be called before commitTransaction()

Solution

  1. Step 1: Review transaction usage in operations

    Operations inside a transaction must include the session option to be part of it.
  2. Step 2: Check the insertOne call

    The insertOne call lacks the {session} option, so it is not part of the transaction.
  3. Final Answer:

    Missing session option in insertOne operation -> Option A
  4. 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?
hard
A. const session = client.startSession(); session.startTransaction(); await collection.insertOne(doc1, {session}); await collection.insertOne(doc2, {session}); await session.commitTransaction(); session.endSession();
B. const session = client.startSession(); await collection.insertOne(doc1); await collection.insertOne(doc2); session.startTransaction(); await session.commitTransaction(); session.endSession();
C. const session = client.startSession(); session.startTransaction(); await collection.insertOne(doc1); await collection.insertOne(doc2); session.abortTransaction(); session.endSession();
D. const session = client.startSession(); await session.startTransaction(); await collection.insertOne(doc1, {session}); await collection.insertOne(doc2, {session}); await session.abortTransaction(); session.endSession();

Solution

  1. Step 1: Understand transaction requirements

    All operations must be inside a started transaction and include the session option.
  2. 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.
  3. Final Answer:

    const session = client.startSession(); session.startTransaction(); await collection.insertOne(doc1, {session}); await collection.insertOne(doc2, {session}); await session.commitTransaction(); session.endSession(); -> Option A
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard