MongoDB Concurrent Access: Patterns
MongoDB Concurrent Access: Patterns
MongoDB Concurrent Access: Patterns
Tip: Optimistic Concurrency
$collection->updateOne(
['_id' => $id, 'version' => $currentVersion],
['$set' => $data, '$inc' => ['version' => 1]]
);
Gotcha: Write Conflicts
MongoDB detects write conflicts at the storage engine level and retries automatically.
Tip: Find and Modify
$collection->findOneAndUpdate(
['status' => 'pending'],
['$set' => ['status' => 'processing']]
);
Atomic operation.
Gotcha: Read Isolation
MongoDB reads are not isolated. A read during a write may see partial results.
Tip: Read Concern
'readConcern' => ['level' => 'majority']
Ensures reads are acknowledged by majority.
Gotcha: Multi-Document Operations
Without transactions, multi-document operations aren't atomic.
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
MongoDB uses document-level locking (WiredTiger storage engine), which means concurrent writes to different documents don't block each other. This is a significant improvement over the older MMAPv1 engine. But operations on the same document still execute sequentially. For high-contention documents (like counters or balances), I use atomic update operators ($inc, $min, $max) instead of read-modify-write patterns to avoid race conditions.
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/)