# WriteConflict：由于对同一文档的并发更新导致写入冲突

- **ID:** `data/mongodb-write-conflict-retry`
- **领域:** data
- **类别:** runtime_error
- **错误码:** `WriteConflict`
- **验证级别:** ai_generated
- **修复率:** 78%

## 根因

MongoDB 的 WiredTiger 存储引擎检测到写入-写入冲突，当两个操作试图同时修改同一文档时，其中一个必须重试。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| MongoDB 4.4 | active | — | — |
| MongoDB 5.0 | active | — | — |
| MongoDB 6.0 | active | — | — |
| MongoDB 7.0 | active | — | — |

## 解决方案

1. ```
   Implement retry logic in the application with exponential backoff. Example in Node.js: `async function updateWithRetry(collection, filter, update, retries=3) { for (let i = 0; i < retries; i++) { try { return await collection.updateOne(filter, update); } catch (e) { if (e.code !== 112) throw e; await new Promise(r => setTimeout(r, 100 * Math.pow(2, i))); } } throw new Error('Max retries exceeded'); }`
   ```
2. ```
   Use optimistic concurrency control with a version field: add a `__v` field to the document and increment it on each update; the update condition includes the current version.
   ```
3. ```
   Reduce the likelihood of conflicts by sharding the collection on a field that distributes writes evenly across documents.
   ```

## 无效尝试

- **** — Unacknowledged writes can silently lose data and still cause conflicts at the storage engine level. (75% 失败率)
- **** — The operation is atomic but still subject to WiredTiger's conflict detection; a retry is necessary. (50% 失败率)
- **** — The conflict is not a timeout issue; it's a concurrent modification that must be retried or avoided. (60% 失败率)
