$ lexprog.com

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

[July 29, 2026] MongoDB

MongoDB Transactions in Laravel

MongoDB Transactions: Tips & Tricks

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

MongoDB Transactions: Tips & Tricks

Tip: Multi-Document Transactions

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

MongoDB 4.0+ supports ACID transactions.

Gotcha: Transactions Need Replica Set

Single-node MongoDB doesn't support transactions. You need a replica set, even with one node.

Tip: Timeout Configuration

DB::connection('mongodb')->transaction(
    function ($session) { /* ... */ },
    ['maxCommitTimeMS' => 3000]
);

Prevents long-running transactions from blocking.

Gotcha: Transactions Lock Resources

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

Tip: Manual Transaction Control

$session = DB::connection('mongodb')->startSession();
$session->startTransaction();

try {
    // Operations
    $session->commitTransaction();
} catch (Exception $e) {
    $session->abortTransaction();
    throw $e;
}

Gotcha: Read Concern in Transactions

Within a transaction, reads see the transaction's own writes, even before commit.

Tip: Transaction Retry Logic

DB::connection('mongodb')->transaction(function ($session) {
    // MongoDB may retry on transient errors
}, ['maxRetries' => 3]);

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

One MongoDB antipattern I've repeatedly encountered is using the database for cross-document joins that should be handled in application code. MongoDB's $lookup is not a SQL JOIN — it's a left outer join with equality match only. Complex relationships across collections are often better handled by embedding related data or maintaining denormalized references. The application code that resolves references is explicit and debuggable; the $lookup pipeline that silently joins ten collections is neither.

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