How can I prefer a specific MongoDB replica set member be elected as primary? I have a replica set with 5 members. replica-1 is a primary and other replicas are secondary:


replica-1 (primary)
replica-2 (secondary)
replica-3 (secondary)
replica-4 (secondary)
replica-5 (secondary)


If the primary replica (replica-1) goes down one of the secondaries will switch to primary. After fixing any issues I will bring up replica-1. Then I need replica-1 to become the primary again. 

How do I achieve this? I have tried using the following command but any of the secondaries may be elected:

rs.stepDown()


How can I force replica-1 to be primary?
You can influence the outcome of elections by adjusting the priority for specific members. The default priority of 1 can be changed to any floating point value between 0 and 1000 (where 0 indicates a non-electable member).

For your use case, you might want to set your preferred primary to have a priority of 10. The priority value doesn't have any special significance aside from numerical ordering for all member priorities. For example: priority values of 1.01, 10, or 1000 are all higher than the default priority of 1.

Note: using priorities may result in extra elections to ensure a preferred member becomes primary when eligible. Typically it is best to think about replica set members as peers with similar resources so that any member can take on the role of primary. Unless there is a strong reason to have a specific member as primary (for example, a replica set distributed across multiple data centres), I would avoid using priorities or consider having a few preferred members with equal priorities in order to minimise elections.

An example sequence with replica-1 having a higher priority (10) than all other members with default priority (1):


replica-1 is current primary.
replica-1 is shutdown in order to be upgraded.
replica-2 is elected as the new primary.
replica-1 is restarted and resumes syncing in order to catch up with the current primary.
replica-1 catches up with the current primary and triggers an election so it can become primary.  replica-2 will drop all current connections when it steps down to a secondary.


Setting replica-1 and  replica-2 to the same priority would avoid the extra election.