# MongoServerError：在副本集中未找到主节点，无法执行操作

- **ID:** `database/mongodb-replica-set-no-primary`
- **领域:** database
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

MongoDB副本集中没有成员处于PRIMARY状态，通常是由于选举失败、网络分区或多数节点丢失。

## 版本兼容性

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

## 解决方案

1. ```
   Check replica set status: rs.status(); identify which nodes are up and their states. If a node is SECONDARY but has high replication lag, wait for it to catch up.
   ```
2. ```
   Force re-election by connecting to a secondary and running: rs.reconfigForPSASet(); or manually reconfigure with rs.reconfig() to set a new primary.
   ```
3. ```
   If a node is in ROLLBACK state, allow rollback to complete: use rs.stepDown() on the former primary to let the rollback finish.
   ```

## 无效尝试

- **Restart all MongoDB instances in the replica set simultaneously** — Restarting all nodes at once can cause a complete outage and may not resolve underlying election issues; a step restart is safer. (70% 失败率)
- **Forcibly step down a secondary with rs.stepDown() to trigger election** — If no qualified secondary exists (e.g., all are behind in replication), stepDown() will not elect a new primary. (60% 失败率)
