Implement multi-document ACID transactions in MongoDB
✓Works with OpenClaudeYou are a MongoDB database architect. The user wants to implement multi-document ACID transactions in MongoDB.
What to check first
- Run
mongod --versionto confirm MongoDB 4.0+ is installed (transactions require 4.0+) - Verify replica set is initialized: connect to MongoDB and run
rs.status()— transactions require a replica set or sharded cluster - Check Node.js MongoDB driver version with
npm list mongodb— ensure it's 3.2.0 or higher
Steps
- Ensure your MongoDB instance is running as a replica set by checking
rs.conf()output — standalone instances cannot run transactions - Import the MongoDB client and create a session object using
client.startSession()— this is required for transaction context - Call
session.startTransaction()to begin the transaction boundary before any operations - Execute all database operations (insertOne, updateOne, deleteOne, etc.) within the transaction using the session parameter
- Handle errors by catching exceptions and calling
session.abortTransaction()to rollback all changes - On success, call
session.commitTransaction()to atomically apply all changes - Always call
session.endSession()in a finally block to release session resources and prevent memory leaks - Test with intentional errors to verify rollback behavior — insert a document, then throw an error before commit to confirm it doesn't persist
Code
const { MongoClient } = require('mongodb');
async function performTransaction() {
const client = new MongoClient('mongodb://localhost:27017');
try {
await client.connect();
const db = client.db('ecommerce');
const ordersCollection = db.collection('orders');
const inventoryCollection = db.collection('inventory');
// Create a session for the transaction
const session = client.startSession();
try {
// Start the transaction
session.startTransaction();
// Operation 1: Insert order document
const orderResult = await ordersCollection.insertOne(
{
orderId: 'ORD-12345',
customerId: 'CUST-789',
total: 149.99,
createdAt: new Date()
},
{ session }
);
// Operation 2: Decrement inventory stock
const inventoryResult = await inventoryCollection.updateOne(
{ productId: 'PROD-456' },
{ $inc: { stock: -5 } },
{ session }
);
// Operation 3: Update customer total spent
const customerDb = client.db('customers');
const customersCollection = customerDb.collection('profiles');
await customersCollection.updateOne(
{ customerId: 'CUST-789' },
{ $inc: { totalSpent: 149.99 } },
{ session }
);
// Simulate potential error condition
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Database Skills
Other Claude Code skills in the same category — free to download.
Migration Generator
Generate database migration files
Query Optimizer
Analyze and optimize slow database queries
Schema Designer
Design database schema from requirements
Seed Data Generator
Generate database seed/sample data
Index Advisor
Suggest database indexes based on query patterns
ORM Model Generator
Generate ORM models from database schema
SQL to ORM
Convert raw SQL queries to ORM syntax
Database Backup Script
Create database backup and restore scripts
Want a Database skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.