Elections
Elections: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 63 of 100
Elections
Foundations & CRUD ✓ → Queries & Schema ✓ → Aggregation & Scale → Atlas & Projects
Aggregation & Scale · 3 — Pipelines · ~10 min · MongoDB — Replication & Sharding
What is this?
Elections choose which member becomes primary. Voting members cast votes based on priority, optime freshness, and connectivity. A majority of votes is required.
Why should you care?
Understanding elections helps you set priorities, arbiters, and member counts so the set recovers predictably.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
rs.conf()
rs.status().members.forEach(m => {
print(m.name, m.stateStr, "prio=" + (rs.conf().members.find(c => c.host === m.name) || {}).priority)
})
// Raise priority example (careful in prod):
// cfg = rs.conf(); cfg.members[0].priority = 2; rs.reconfig(cfg)
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- rs.conf shows configured priorities.
- rs.status shows current states.
- Higher priority members are preferred as primary if they are caught up.
- Reconfig changes election behavior — use carefully.
Practice next
- Print rs.conf() and note votes and priority.
- Identify who can vote.
- In a lab, set a preferred primary with higher priority.
- Read about term and electionId in rs.status().
- Add an arbiter only if you truly need odd votes without more data copies.
Remember
Elections pick the primary. Majority vote is required. Priority influences who wins.
Preferred primary in the main DC
Ops sets higher priority on the in-region member closest to app servers.
Outcome: After maintenance, write traffic returns to the preferred DC.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!