A client session is an application-created MongoDB context that groups related operations. Transactions use it to preserve operation order, causal relationships, and transaction settings across a deployment. section 8.4.1
Use a session when implementing a transaction:
- Start a logical session and associate every transaction operation with it. section 8.4.1
- Configure read concern, write concern, and read preference when starting the transaction. section 8.4.2
- End the session after commit, abort, or a failed attempt; retry labeled transient or unknown commit errors when appropriate. section 8.4.2
The Core API exposes transaction control and retry handling explicitly. Callback APIs simplify the workflow: a callback runs through withTransaction, which starts, commits, aborts, and retries the transaction automatically. section 8.4.1 section 8.4.3
Retrying a mongosh transaction
A retry loop creates a session for each attempt, passes it to executeTransaction, ends it in finally, and retries TransientTransactionError or UnknownTransactionCommitResult up to five times. The transaction function reads an account, updates accounts and customers, and inserts a transaction document before committing. section 8.4.2
Listing 8.1 Executing a multidocument transaction in mongosh
function executeTransaction(session) {
const dbSampleAnalytics = session.getDatabase('sample_analytics')
session.startTransaction({
readConcern: { level: 'snapshot' },
writeConcern: { w: 'majority' },
readPreference: 'primary'
})
try {
const account = dbSampleAnalytics.accounts.findOne
➥({ account_id: 371138 })
if (!account) {
throw new Error('Account not found')
}
const newTransactionCount = (account.transaction_count || 0) + 1
dbSampleAnalytics.accounts.updateOne(
{ account_id: 371138 },
{ $set: { limit: 12000, last_transaction_date: new Date() },
$inc: { transaction_count: 1 }
}
)
dbSampleAnalytics.customers.updateMany(
{ accounts: { $in: [371138] } },
{ $inc: { transaction_count: 1 },
$set: { last_transaction_date: new Date() }
}
)
dbSampleAnalytics.transactions.insertOne({
account_id: 371138,
transaction_count: newTransactionCount,
date: new Date(),
amount: 1500,
transaction_code: 'buy'
})
session.commitTransaction()
} catch (error) {
session.abortTransaction()
throw error;
}
}
Inspect the complete mongosh flow for starting a session transaction, applying options, performing multidocument operations, and committing or aborting. section 8.4.2




