Prevent Secondary from Becoming Primary

Overview

In a replica set, by default all secondary members are eligible tobecome primary through the election process. You can use thepriority to affect theoutcome of these elections by making some members more likely to becomeprimary and other members less likely or unable to become primary.

Secondaries that cannot become primary are also unable to triggerelections. In all other respects these secondaries are identical to othersecondaries.

To prevent a secondary member from ever becoming a primaryin a failover, assign the secondary a priority of 0, asdescribed here. For a detailed description of secondary-only members and their purposes,see Priority 0 Replica Set Members.

Considerations

When updating the replica configuration object, access the replica setmembers in the members array with thearray index. The array index begins with 0. Do not confusethis index value with the value of themembers[n]._id field in each document inthe members array.

Note

MongoDB does not permit the current primary to have a priorityof 0. To prevent the current primary from again becoming a primary,you must first step down the current primary usingrs.stepDown().

Procedure

This tutorial uses a sample replica set with 5 members.

Warning

  • The rs.reconfig() shell method can force the currentprimary to step down, which causes an election. When the primary steps down, themongod closes all client connections. While thistypically takes 10-20 seconds, try to make these changes duringscheduled maintenance periods.
  • Avoid reconfiguring replica sets that contain members of differentMongoDB versions as validation rules may differ across MongoDB versions.

Retrieve the current replica set configuration.

The rs.conf() method returns a replica setconfiguration document thatcontains the current configuration for a replica set.

In a mongo shell connected to a primary, run thers.conf() method and assign the result to a variable:

  1. cfg = rs.conf()

The returned document contains amembers field which contains an arrayof member configuration documents, one document for each member of thereplica set.

Assign priority value of 0.

To prevent a secondary member from becoming a primary, update thesecondary member’s members[n].priorityto 0.

To assign a priority value to a member of the replica set, access themember configuration document using the array index. In thistutorial, the secondary member to change corresponds to theconfiguration document found at position 2 of themembers array.

  1. cfg.members[2].priority = 0

The configuration change does not take effect until you reconfigurethe replica set.

Reconfigure the replica set.

Use rs.reconfig() method to reconfigure the replica setwith the updated replica set configuration document.

Pass the cfg variable to the rs.reconfig() method:

  1. rs.reconfig(cfg)