const session = db.getMongo().startSession()Transactions are associated with a client session.
Use sessions, multi-document transactions, and change streams for modern event-driven and consistency-sensitive MongoDB applications.
Use client sessions and transaction boundaries in mongosh.
const session = db.getMongo().startSession()Transactions are associated with a client session.
session.startTransaction()Transactions are available on deployments that support them, such as replica sets.
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.
session.abortTransaction()Useful when an error or validation failure occurs mid-flow.
session.endSession()A good habit after session-based work.
Listen for inserts, updates, and deletes as they happen.
const stream = db.orders.watch()Change streams let applications react to new writes in near real time.
Filter stream events with a pipeline.
const stream = db.orders.watch([{ $match: { operationType: "insert" } }])Filtering early helps keep change events focused and lighter to process.
stream.next()Useful for testing and interactive exploration.