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
Start a session
const session = db.getMongo().startSession()

# Create a session for transactional work.

Start a transaction
session.startTransaction()

# Begin a multi-document transaction.

Transaction example
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();
}

# Insert and update as one transaction.

Abort a transaction
session.abortTransaction()

# Roll back a started transaction.

End a session
session.endSession()

# Clean up the session after work completes.

## Change streams
Watch a collection
const stream = db.orders.watch()

# Open a change stream on one collection.

Watch only selected changes
const stream = db.orders.watch([{ $match: { operationType: "insert" } }])

# Filter stream events with a pipeline.

Read the next change event
stream.next()

# Consume the stream in mongosh.

Recommended next

No recommendations yet.