MongoDB Bulk Operations Interview Questions

Introduction

This guide covers essential MongoDB bulk operations commonly asked in technical interviews. Each question includes detailed answers and practical examples.

Medium

1. What are MongoDB bulk operations and when should you use them?

MongoDB bulk operations allow you to perform multiple write operations in a single request:

  • Insert multiple documents
  • Update multiple documents
  • Delete multiple documents
  • Mix different operations
Use Cases:
  • Data migration and import
  • Batch processing
  • Performance optimization
  • Atomic operations
Hard

2. What is the difference between ordered and unordered bulk operations?

MongoDB supports both ordered and unordered bulk operations:

1. Ordered Operations
// Ordered bulk operations (default)
db.users.bulkWrite([
    { insertOne: { document: { name: "John" } } },
    { updateOne: { 
        filter: { name: "John" },
        update: { $set: { status: "active" } }
    }},
    { deleteOne: { filter: { name: "John" } } }
], { ordered: true })

Characteristics:

  • Operations execute in sequence
  • Stops on first error
  • Slower but predictable
  • Useful for dependent operations
2. Unordered Operations
// Unordered bulk operations
db.users.bulkWrite([
    { insertOne: { document: { name: "John" } } },
    { updateOne: { 
        filter: { name: "Jane" },
        update: { $set: { status: "active" } }
    }},
    { deleteOne: { filter: { name: "Bob" } } }
], { ordered: false })

Characteristics:

  • Operations execute in parallel
  • Continues despite errors
  • Faster but less predictable
  • Useful for independent operations
Hard

3. How do you optimize bulk operations for performance?

Optimizing bulk operations involves several strategies:

1. Batch Size Optimization
// Optimal batch size (1000-5000 operations)
const batchSize = 1000;
const operations = [];

// Prepare operations
for (let i = 0; i < documents.length; i += batchSize) {
    const batch = documents.slice(i, i + batchSize);
    operations.push({
        insertMany: {
            documents: batch
        }
    });
}

// Execute in batches
for (const batch of operations) {
    await db.users.bulkWrite([batch], { ordered: false });
}
2. Write Concern and Performance
// Optimize write concern for bulk operations
db.users.bulkWrite([
    { insertOne: { document: { name: "John" } } },
    { updateMany: { 
        filter: { status: "inactive" },
        update: { $set: { status: "active" } }
    }}
], {
    ordered: false,
    writeConcern: { w: 0 }, // Unacknowledged writes
    bypassDocumentValidation: true
})
Medium

4. What are the different types of bulk operations available?

MongoDB provides several types of bulk operations:

// 1. Insert Operations
db.users.bulkWrite([
    { insertOne: { document: { name: "John" } } },
    { insertMany: { 
        documents: [
            { name: "Jane" },
            { name: "Bob" }
        ]
    }}
])

// 2. Update Operations
db.users.bulkWrite([
    { updateOne: {
        filter: { name: "John" },
        update: { $set: { status: "active" } }
    }},
    { updateMany: {
        filter: { status: "inactive" },
        update: { $set: { status: "active" } }
    }}
])

// 3. Delete Operations
db.users.bulkWrite([
    { deleteOne: { filter: { name: "John" } } },
    { deleteMany: { filter: { status: "inactive" } } }
])

// 4. Replace Operations
db.users.bulkWrite([
    { replaceOne: {
        filter: { name: "John" },
        replacement: { name: "John", status: "active" }
    }}
])
Hard

5. How do you handle errors in bulk operations?

Error handling in bulk operations requires careful consideration:

1. Error Handling Strategies
try {
    const result = await db.users.bulkWrite([
        { insertOne: { document: { name: "John" } } },
        { updateOne: { 
            filter: { name: "Jane" },
            update: { $set: { status: "active" } }
        }},
        { deleteOne: { filter: { name: "Bob" } } }
    ], { ordered: false });

    console.log('Success:', result);
} catch (error) {
    if (error.writeErrors) {
        // Handle individual operation errors
        error.writeErrors.forEach(writeError => {
            console.error('Operation failed:', writeError);
        });
    }
    
    if (error.writeConcernError) {
        // Handle write concern errors
        console.error('Write concern error:', error.writeConcernError);
    }
}
2. Retry Logic
async function bulkWriteWithRetry(operations, maxRetries = 3) {
    let retries = 0;
    
    while (retries < maxRetries) {
        try {
            const result = await db.users.bulkWrite(operations, {
                ordered: false
            });
            return result;
        } catch (error) {
            retries++;
            
            if (retries === maxRetries) {
                throw error;
            }
            
            // Wait before retrying (exponential backoff)
            await new Promise(resolve => 
                setTimeout(resolve, Math.pow(2, retries) * 1000)
            );
        }
    }
}

Next Steps

Continue your MongoDB interview preparation with: