Starting a Session and Multi-Document Transaction
Learners will open a ClientSession, execute multiple operations inside startTransaction(), and commit or abort the transaction.
Sessions Are the Foundation
MongoDB multi-document transactions require a session. A session is a server-side context that tracks your causally consistent reads and transaction state. You create a session from the MongoClient, pass it to every operation inside the transaction, and then end the session when you are done. Forgetting to pass the session object means operations run outside the transaction and are not rolled back on abort.
Creating a Session With startSession()
Call client.startSession() to obtain a ClientSession object. This does not start a transaction yet—it only establishes the server-side context. Sessions can optionally be configured for causal consistency so that reads within the session always reflect all prior writes in the same session, even on secondaries. Always end the session in a finally block to release server resources.
const { MongoClient } = require('mongodb');
const client = new MongoClient(process.env.MONGODB_URI);
async function run() {
const session = client.startSession();
try {
// ... use session here
} finally {
await session.endSession();
await client.close();
}
}All lessons in this course
- ACID Guarantees in a Distributed Document Store
- Starting a Session and Multi-Document Transaction
- Error Handling and Retry Logic
- Transaction Performance Considerations