# MongoServerError: 由于分片块迁移进行中，事务已中止

- **ID:** `mongodb/transaction-abort-on-shard-migration`
- **领域:** mongodb
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

多文档事务访问了一个正在分片之间迁移的块，导致平衡器中止了该事务。

## 版本兼容性

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

## 解决方案

1. ```
   Implement a retry loop with exponential backoff to re-run the transaction after a delay: while (true) { try { session.startTransaction(); ... session.commitTransaction(); break; } catch (e) { if (e.code === 251) { sleep(1000 * Math.pow(2, retries)); retries++; } else throw e; } }
   ```
2. ```
   Temporarily disable the balancer during critical transaction windows: sh.stopBalancer(); // run transactions; sh.startBalancer()
   ```
3. ```
   Avoid accessing chunks that are being migrated by querying the config.changelog collection to check for recent migrations and routing transactions to stable chunks: use config.changelog to identify migration patterns
   ```

## 无效尝试

- **** — Stopping the balancer is not a fix for the transaction; it only avoids the symptom but can cause performance issues. (50% 失败率)
- **** — The abort is triggered by the migration process, not by timeout. (90% 失败率)
- **** — The migration is asynchronous and may take seconds to minutes to complete. (70% 失败率)
