A "WriteConflict" error in MongoDB occurs when two or more operations try to modify the same document or index entry at the same time. MongoDB uses an optimistic concurrency control model, so it doesn't lock documents in a traditional way—this means conflicts can happen if concurrent writes collide.
🔍 What Causes a WriteConflict?
Here are common scenarios:
-
Concurrent Updates to the Same Document
Two clients try to update the same document at the same time. -
Secondary Index Updates
When two operations try to update fields that affect the same secondary index entry. -
Long-running Writes or Reads
A write operation that takes a while may overlap with another that tries to modify the same data. -
Aggressive Parallelism
Bulk writes, aggregation pipelines with$merge
, or$out
, or scripts with high concurrency can lead to overlapping writes.
✅ How to Handle WriteConflict Errors
1. Retry the Operation
MongoDB automatically retries internal operations in many cases, but if you're writing your own logic (e.g., in a script or app), you may need to implement a retry mechanism:
2. Reduce Contention
-
Avoid multiple clients writing to the same document at once.
-
Split data so concurrent operations don’t overlap on the same fields or records.
-
Restructure your data model to reduce write "hotspots."
3. Use $merge
with whenMatched: "merge"
Carefully
If using aggregation pipelines with $merge
, and you're merging into the same collection, avoid matching on _id
only. Consider conflict resolution logic or redirecting updates to separate collections.
4. Avoid Hot Documents
When multiple operations frequently write to the same document (e.g., a counter or stats object), consider redesigning:
-
Use a queue or debounce mechanism to delay and batch writes.
Summary
-
What it is: A concurrency error when simultaneous writes collide.
-
How to handle: Implement retry logic, reduce write contention, and optimize your schema.