How to Commit a Transaction in MongoDB: Simple Guide
To commit a transaction in MongoDB, you first start a session and a transaction using
startSession() and startTransaction(). After performing your operations, call commitTransaction() on the session to save all changes atomically.Syntax
Here is the basic syntax to commit a transaction in MongoDB using the Node.js driver:
const session = client.startSession();- starts a new session.session.startTransaction();- begins the transaction.- Perform your database operations inside the transaction.
await session.commitTransaction();- commits all operations atomically.session.endSession();- ends the session.
javascript
const session = client.startSession(); session.startTransaction(); try { // perform operations await session.commitTransaction(); } catch (error) { await session.abortTransaction(); } finally { await session.endSession(); }
Example
This example shows how to transfer money between two accounts using a transaction. It commits the transaction to save both debit and credit operations together.
javascript
const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const session = client.startSession(); try { session.startTransaction(); const accounts = client.db('bank').collection('accounts'); // Debit 100 from account A await accounts.updateOne({ accountId: 'A' }, { $inc: { balance: -100 } }, { session }); // Credit 100 to account B await accounts.updateOne({ accountId: 'B' }, { $inc: { balance: 100 } }, { session }); await session.commitTransaction(); console.log('Transaction committed successfully'); } catch (error) { await session.abortTransaction(); console.error('Transaction aborted due to error:', error); } finally { await session.endSession(); await client.close(); } } run();
Output
Transaction committed successfully
Common Pitfalls
Common mistakes when committing transactions in MongoDB include:
- Not starting a session before starting a transaction.
- Forgetting to pass the
sessionobject to all operations inside the transaction. - Not handling errors properly, which can leave transactions open.
- Trying to commit a transaction after the session has ended.
Always use try/catch/finally to commit or abort transactions and end the session.
javascript
/* Wrong way: Missing session in operations */ const session = client.startSession(); session.startTransaction(); await collection.insertOne({ name: 'test' }); // Missing { session } await session.commitTransaction(); session.endSession(); /* Right way: Pass session to operations */ const session = client.startSession(); session.startTransaction(); await collection.insertOne({ name: 'test' }, { session }); await session.commitTransaction(); await session.endSession();
Quick Reference
Remember these key points when committing transactions in MongoDB:
- Always start a session with
startSession(). - Begin the transaction with
startTransaction(). - Pass the session to all database operations inside the transaction.
- Commit the transaction with
commitTransaction()to save changes. - Abort the transaction with
abortTransaction()on errors. - End the session with
endSession()to free resources.
Key Takeaways
Start a session and transaction before performing operations to use transactions in MongoDB.
Always pass the session object to all operations inside the transaction to include them in the commit.
Use commitTransaction() to save all changes atomically and abortTransaction() to cancel on errors.
Handle errors with try/catch and always end the session to avoid resource leaks.
Transactions ensure multiple operations succeed or fail together, keeping data consistent.