November 7th: Exploring an 80% lower cost hosted Redis alternative - register

Question: How do you change the primary node in a MongoDB replica set?

Answer

In a MongoDB replica set, the primary node is responsible for handling all write operations. However, there might be situations where you need to switch the role of the primary node manually, such as for maintenance purposes. The process of changing the primary node in a MongoDB replica set involves forcing the current primary to step down, which triggers an automatic election among the remaining secondary nodes.

Step 1: Connect to the Current Primary Node

Use the mongo shell to connect to your current primary node:

mongo --host currentPrimaryHost:port

Replace currentPrimaryHost:port with the address and port of your current primary node.

Step 2: Use the rs.stepDown() Command

Once connected, use the rs.stepDown() command to force the primary node to step down:

rs.stepDown()

This command will make the current primary node step down and become a secondary node. The replica set will then automatically initiate an election to choose a new primary from the available secondary nodes.

Optional: Specify Step Down Period

You can specify how long the current primary should wait before it can become primary again by passing an argument to rs.stepDown():

rs.stepDown(60)

This example sets the step-down period to 60 seconds, during which the node cannot become primary again.

Monitoring the Election Process

You can monitor the election process and check the status of your replica set members by using the rs.status() command:

rs.status()

Look for the stateStr field in the output to identify the new primary node. The value PRIMARY indicates the current primary node.

Considerations

  • Ensure that your replica set has a majority of nodes available to successfully elect a new primary.
  • The automatic failover process may temporarily impact your application's ability to perform write operations until a new primary is elected.
  • It's recommended to perform such operations during maintenance windows or periods of low traffic to minimize impact.

Changing the primary node manually is generally used for administrative tasks. MongoDB's replica sets are designed to automatically manage primary elections in response to network partitions or node failures.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost