Problem Statement
When does an election occur in a MongoDB replica set?
Explanation
Elections occur when the primary node becomes unavailable due to network issues, crashes, or planned maintenance. The replica set members automatically vote to elect a new primary from the available secondaries.
The election process ensures that the replica set always has a primary to accept writes. Elections use a consensus algorithm where members with higher priority and more recent data are more likely to be elected. During an election, writes are not accepted, but the process typically completes in seconds.
Code Solution
SolutionRead Only
// Force an election by stepping down primary
rs.stepDown(60) // Step down for 60 seconds
// Check election status
rs.status().members.forEach(m => {
print(m.name + ": " + m.stateStr)
})
// Set member priority (higher priority more likely to be elected)
var cfg = rs.conf()
cfg.members[0].priority = 2
rs.reconfig(cfg)