CodeToLive

MongoDB Transactions

Implement ACID transactions in MongoDB for multi-document operations.

Basic Transaction

// Using the MongoDB shell
session = db.getMongo().startSession()
session.startTransaction()

try {
    db.accounts.updateOne(
        { _id: "A" },
        { $inc: { balance: -100 } },
        { session }
    )
    
    db.accounts.updateOne(
        { _id: "B" },
        { $inc: { balance: 100 } },
        { session }
    )
    
    session.commitTransaction()
} catch (error) {
    session.abortTransaction()
    throw error
} finally {
    session.endSession()
}

Node.js Driver Example

const session = client.startSession();
try {
    await session.withTransaction(async () => {
        await accounts.updateOne(
            { _id: "A" },
            { $inc: { balance: -100 } },
            { session }
        );
        
        await accounts.updateOne(
            { _id: "B" },
            { $inc: { balance: 100 } },
            { session }
        );
    });
} finally {
    await session.endSession();
}

Transaction Options

session.startTransaction({
    readConcern: { level: "snapshot" },
    writeConcern: { w: "majority" },
    readPreference: "primary"
});

Best Practices

  • Keep transactions short (under 1 second)
  • Use retry logic for transient errors
  • Design applications to handle failed transactions
  • Monitor transaction performance metrics
  • Consider using change streams for complex workflows
← Back to Tutorials