MongoDB Transactions and Change Streams

Use sessions, multi-document transactions, and change streams for modern event-driven and consistency-sensitive MongoDB applications.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Transactions

Use client sessions and transaction boundaries in mongosh.

Start a session

Create a session for transactional work.

javascriptANYmongodbsessiontransactions
javascript
const session = db.getMongo().startSession()

Transactions are associated with a client session.

Start a transaction

Begin a multi-document transaction.

javascriptANYmongodbtransactionstart
javascript
session.startTransaction()

Transactions are available on deployments that support them, such as replica sets.

Transaction example

Insert and update as one transaction.

javascriptANYmongodbtransactionsexample
javascript
const session = db.getMongo().startSession();
const appdb = session.getDatabase("appdb");

session.startTransaction();
try {
  appdb.accounts.updateOne({ _id: 1 }, { $inc: { balance: -50 } });
  appdb.accounts.updateOne({ _id: 2 }, { $inc: { balance: 50 } });
  session.commitTransaction();
} catch (err) {
  session.abortTransaction();
  throw err;
} finally {
  session.endSession();
}

A classic transfer example: either both updates commit or neither does.

Abort a transaction

Roll back a started transaction.

javascriptANYmongodbtransactionabort
javascript
session.abortTransaction()

Useful when an error or validation failure occurs mid-flow.

End a session

Clean up the session after work completes.

javascriptANYmongodbsessioncleanup
javascript
session.endSession()

A good habit after session-based work.

Change streams

Listen for inserts, updates, and deletes as they happen.

Watch a collection

Open a change stream on one collection.

javascriptANYmongodbchange-streamswatch
javascript
const stream = db.orders.watch()

Change streams let applications react to new writes in near real time.

Watch only selected changes

Filter stream events with a pipeline.

javascriptANYmongodbchange-streamspipeline
javascript
const stream = db.orders.watch([{ $match: { operationType: "insert" } }])

Filtering early helps keep change events focused and lighter to process.

Read the next change event

Consume the stream in mongosh.

javascriptANYmongodbchange-streamsevents
javascript
stream.next()

Useful for testing and interactive exploration.

Recommended next

No recommendations yet.