A replica-set election is MongoDB’s process for selecting a primary when a replica set is initialized, changes membership, or loses contact with its current primary. Members vote under protocol version 1, based on the Raft consensus algorithm. section 9.1.2
Key operational points include:
- A node addition or removal, replica-set initialization, or a primary heartbeat failure lasting longer than the default 10-second timeout can trigger an election. section 9.1.2
- The member with the most up-to-date write timestamp has the highest probability of becoming primary, reducing rollback risk after reintegration. section 9.1.2
- Writes pause during an election, while reads may continue through secondaries configured to serve them. A standard election usually completes within 12 seconds. section 9.1.2
- Terms prevent double voting and help detect simultaneous primaries; a freeze period limits successive elections. The election timeout is configurable with settings.electionTimeoutMillis. section 9.1.2
- An arbiter can vote without storing data or becoming primary, while a hidden member can vote but cannot become primary or accept client reads. section 9.1.1
Inspect the elected primary
Run db.adminCommand("replSetGetStatus").members.map((m) => ({ _id: m._id, name: m.name, state: m.state, stateStr: m.stateStr })). The result identifies PRIMARY and SECONDARY members by state and stateStr, making the current election outcome visible. The same status information can distinguish STARTUP2, RECOVERING, DOWN, ROLLBACK, and other member states. section 9.1.1
Figure 9.1 The election mechanism within a MongoDB replica set is activated when the primary node becomes nonoperational. The secondary replicas vote to elect a new primary. (Image © MongoDB 2024 CC BY-NC-SA 3.0)
Use the election diagram to follow how secondary replicas vote for a new primary after the current primary becomes unavailable. section 9.1.2
