liveBook · Manning

Session

As explained in MongoDB 8.0 in Action, Third Edition

A client session is an application-created MongoDB session context that groups operations and supports transactions, ordering, and related settings.

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

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Explains session association, transaction options, cleanup, and labeled-error retries through mongosh and driver examples.
Examples
Demonstrates account, customer, and transaction updates using mongosh, Node.js, PyMongo, and Ruby callback APIs.
What it assumes
Assumes basic MongoDB operations and introduces logical sessions through transaction examples.
What you can do after
Operate/configure transactions by creating sessions, associating operations, selecting concerns, cleaning up, and handling retries.
How it connects
Connects client sessions with transactions, causal consistency, retriable writes, read concern, write concern, read preference, and retry logic.

Also explained in

Compare how 5 books explain session →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.