$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[December 07, 2025] MongoDB

MongoDB Bulk Write Operations

MongoDB Bulk Write Operations

────────────────────────────────────────────────────────

MongoDB Bulk Write Operations

Tip: bulkWrite for Mixed Operations

$collection->bulkWrite([
    ['insertOne' => ['document' => ['title' => 'A']]],
    ['updateOne' => ['filter' => ['title' => 'B'], 'update' => ['$set' => ['status' => 'done']]]],
    ['deleteOne' => ['filter' => ['title' => 'C']]],
]);

Gotcha: Ordered vs Unordered

$collection->bulkWrite($operations, ['ordered' => false]);

Unordered continues after errors. Ordered stops at first failure.

Tip: Bulk Insert Performance

$bulk = new MongoDB\Driver\BulkWrite();
for ($i = 0; $i < 10000; $i++) {
    $bulk->insert(['title' => "Post {$i}"]);
}
$manager->executeBulkWrite('db.posts', $bulk);

Much faster than individual inserts.

Gotcha: Write Concern

['writeConcern' => new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY)]

Ensures writes are replicated to majority of replica set members.

Tip: Bulk Update with Array Filters

['updateMany' => [
    'filter' => [],
    'update' => ['$set' => ['comments.$[elem].approved' => true]],
    'arrayFilters' => [['elem.user_id' => 1]],
]]

Gotcha: Bulk Operation Size

MongoDB has a 100MB limit for bulk operation messages. Split very large batches.

Tip: Embed or Reference? The 80/20 Rule

If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.

Tip: Index Your Query Patterns, Not All Fields

Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.

Gotcha: No Transaction Rollback for Index Builds

Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.

Senior Insight

Bulk write operations in MongoDB are dramatically faster than individual insertOne() calls. I've loaded 100K documents in 2 seconds using bulkWrite() with ordered: false, compared to 45 seconds with individual inserts. The trade-off: unordered bulk writes can succeed partially, with some operations failing and others succeeding. Always check the result for writeErrors and have a retry strategy for failed operations.

Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)

────────────────────────────────────────────────────────
<-- back to posts