Transactions are necessary when multiple operations across one or more collections must be atomic, meaning all succeed or all fail together. Simple single-document operations do not require transactions.
Single-document operations in MongoDB are atomic by default and do not require explicit transactions.
const session = client.startSession(); let finalBalance; await session.withTransaction(async () => { const account = await accounts.findOne({ accountId: 123 }, { session }); await accounts.updateOne({ accountId: 123 }, { $inc: { balance: -100 } }, { session }); finalBalance = account.balance - 100; }); console.log(finalBalance);
The transaction reads the original balance, subtracts 100, updates the document, and sets finalBalance accordingly. After commit, finalBalance reflects the updated balance.
The correct way is to call startSession() on the client, then call startTransaction() on the session object.
All operations inside a transaction must include the session option to be part of the transaction. Missing it means the operation executes outside the transaction.
