Transactions help keep data safe and correct when many changes happen together. But they can slow things down if not used carefully.
0
0
Transaction performance considerations in MongoDB
Introduction
When you need to update several pieces of data at once and want all changes to succeed or fail together.
When you want to avoid errors caused by multiple users changing data at the same time.
When you want to make sure your data stays accurate during complex operations.
When you want to keep your app reliable even if something goes wrong during data changes.
Syntax
MongoDB
const session = client.startSession(); session.startTransaction(); try { // your database operations here await session.commitTransaction(); } catch (error) { await session.abortTransaction(); } finally { session.endSession(); }
Always start a session before beginning a transaction.
Commit the transaction if all operations succeed, otherwise abort it.
Examples
This example shows inserting and updating documents inside a transaction.
MongoDB
const session = client.startSession(); session.startTransaction(); try { await collection.insertOne({name: 'Alice'}, {session}); await collection.updateOne({name: 'Bob'}, {$set: {age: 30}}, {session}); await session.commitTransaction(); } catch (e) { await session.abortTransaction(); } finally { session.endSession(); }
This example deletes a document inside a transaction.
MongoDB
const session = client.startSession(); session.startTransaction(); try { await collection.deleteOne({name: 'Charlie'}, {session}); await session.commitTransaction(); } catch (e) { await session.abortTransaction(); } finally { session.endSession(); }
Sample Program
This program connects to MongoDB, starts a transaction, inserts a user, updates the user's age, and commits the transaction. If any step fails, it aborts the transaction.
MongoDB
const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('testdb'); const collection = db.collection('users'); const session = client.startSession(); try { session.startTransaction(); await collection.insertOne({name: 'Diana', age: 25}, {session}); await collection.updateOne({name: 'Diana'}, {$set: {age: 26}}, {session}); await session.commitTransaction(); console.log('Transaction committed successfully'); } catch (error) { await session.abortTransaction(); console.log('Transaction aborted due to error:', error.message); } finally { session.endSession(); await client.close(); } } run();
OutputSuccess
Important Notes
Keep transactions short to avoid slowing down your database.
Avoid long-running operations inside transactions to reduce waiting time.
Use transactions only when you need multiple operations to succeed or fail together.
Summary
Transactions keep data changes safe and consistent.
They can slow down performance if used too much or for too long.
Use transactions wisely to balance safety and speed.