MongoDB Transactions and Change Streams
Use sessions, multi-document transactions, and change streams for modern event-driven and consistency-sensitive MongoDB applications.
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Transactions
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.
## Change streams
More in MongoDB
MongoDB Backup, Restore, and Replica Set Workflows
Use mongodump, mongorestore, replica set commands, and diagnostic tools for operational MongoDB workflows.
MongoDB Import, Export, and Database Tools
Use mongoimport, mongoexport, bsondump, and GridFS tools for practical MongoDB data movement workflows.
MongoDB Users, Roles, and Administrative Commands
Create users, grant roles, inspect server status, and run the most common administrative commands in MongoDB.
MongoDB Indexes, Explain Plans, and Performance
Create indexes, inspect query plans, and troubleshoot common MongoDB query performance issues.
MongoDB Aggregation Pipeline Patterns
Group, project, sort, unwind, lookup, facet, and aggregate analytics data with MongoDB pipelines.
MongoDB Update Operators and Array Patterns
Use $set, $unset, $inc, $push, $addToSet, positional updates, and arrayFilters for real-world MongoDB mutations.