$ lexprog.com

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

[May 17, 2024] MongoDB

MongoDB Multi-Document Transactions

MongoDB Multi-Document Transactions

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

MongoDB Multi-Document Transactions

Tip: Transaction with Callback

DB::connection('mongodb')->transaction(function ($session) {
    Post::create(['title' => 'New'], ['session' => $session]);
    Category::where('slug', 'tech')
        ->increment('post_count', 1, [], ['session' => $session]);
});

Gotcha: Transactions Need Replica Set

Single-node MongoDB doesn't support transactions. You need a replica set.

Tip: Transaction Timeout

DB::connection('mongodb')->transaction(
    fn($s) => /* ... */,
    ['maxCommitTimeMS' => 3000]
);

Gotcha: Transactions Lock Resources

While a transaction is open, other operations on the same documents may be blocked.

Tip: Retry Logic

DB::connection('mongodb')->transaction(
    fn($s) => /* ... */,
    ['maxRetries' => 3]
);

MongoDB may retry on transient errors.

Gotcha: Cross-Collection Transactions

Transactions work across collections and even databases on the same server.

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

Multi-document transactions (MongoDB 4.0+) bring ACID guarantees to MongoDB, but they come with performance costs. Transactions in MongoDB require a replica set and have a 60-second default timeout. I've seen teams wrap every write in a transaction unnecessarily, killing throughput. Use transactions only when you genuinely need atomic updates across multiple documents. For single-document operations, MongoDB's atomicity is sufficient.

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