Insert and update as one transaction.
Section: Transactions
Transaction example
javascript
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();
}Explanation
A classic transfer example: either both updates commit or neither does.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Transactions