# MongoServerError：事务 1234 因写入冲突而中止

- **ID:** `mongodb/transaction-abort-due-to-write-conflict`
- **领域:** mongodb
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

两个并发事务尝试修改同一文档，导致一个事务因乐观并发控制而中止。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| mongodb-5.0 | active | — | — |
| mongodb-6.0 | active | — | — |
| mongodb-7.0 | active | — | — |
| mongodb-8.0 | active | — | — |

## 解决方案

1. ```
   Implement a retry loop in the application: catch the write conflict error and re-run the transaction up to 3 times with exponential backoff.
   ```
2. ```
   Reduce transaction scope by accessing fewer documents or using smaller batch sizes to minimize contention.
   ```
3. ```
   Use a deterministic ordering for document updates within transactions to prevent deadlocks and conflicts.
   ```

## 无效尝试

- **** — Disabling transactions entirely removes atomicity guarantees for multi-document operations. (50% 失败率)
- **** — Increasing wtimeoutMS does not resolve write conflicts; it only affects write concern timeouts. (50% 失败率)
- **** — Setting retryWrites=true does not apply to transactions; transactions must be retried manually. (50% 失败率)
