mongodb
runtime_error
ai_generated
true
MongoServerError:不是主节点且 slaveOk=false
MongoServerError: not master and slaveOk=false
ID: mongodb/replica-set-election-hiccup
85%修复率
85%置信度
1证据数
2023-06-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| mongodb-3.6 | active | — | — | — |
| mongodb-4.0 | active | — | — | — |
| mongodb-4.2 | active | — | — | — |
| mongodb-4.4 | active | — | — | — |
| mongodb-5.0 | active | — | — | — |
| mongodb-6.0 | active | — | — | — |
| mongodb-7.0 | active | — | — | — |
根因分析
在选举期间,从节点收到了写操作或未启用 slaveOk 的读操作。
English
A secondary replica set member received a write operation or a read without slaveOk enabled during an election.
官方文档
https://www.mongodb.com/docs/manual/reference/method/rs.slaveOk/解决方案
-
Implement automatic retry with exponential backoff for write operations, and use readPreference=secondaryPreferred for reads. Example in Node.js: await collection.insertOne(doc, { w: 'majority', wtimeout: 5000 }).catch(e => { if (e.codeName === 'NotMaster') { /* retry after 1s */ } }) -
Use MongoDB driver's built-in retryWrites and retryReads options (enabled by default in 4.2+). Configure connection string: mongodb://host1,host2,host3/?retryWrites=true&retryReads=true
-
Ensure at least 3 voting members in the replica set to avoid elections causing extended unavailability.
无效尝试
常见但无效的做法:
-
70% 失败
This bypasses read preference and may cause stale reads; it does not fix write failures during elections.
-
90% 失败
Restarting does not resolve the transient election state; it may cause longer downtime.
-
60% 失败
Without proper retry logic with backoff, this can overwhelm the server during elections.