Question: How do you add a member to a MongoDB replica set?

Answer

Adding a member to a MongoDB replica set involves using the rs.add() method from the MongoDB shell. This operation requires administrative privileges, so ensure you have the necessary permissions before proceeding. Here's a step-by-step guide:

  1. Connect to the Primary Node: Open the MongoDB shell and connect to the primary node of your replica set.

  2. Add the New Member: Use the rs.add() command to add a new member to the replica set. You'll need to specify the hostname (and optionally, the port) of the member you wish to add.

rs.add("hostname:port")

If you're adding the member with default settings, specifying the hostname is enough. However, if you need to customize the member’s configuration (e.g., setting it as an arbiter, hidden, or specifying its priority), you should pass a document instead:

rs.add({ host: "hostname:port", arbiterOnly: false, hidden: false, priority: 1, votes: 1 })
  1. Verify the Configuration: After adding the new member, it's important to verify that it has been successfully added to the replica set. You can view the current configuration with the following command:
rs.conf()

This will display the replica set's configuration, including all members. Ensure the new member appears in the list with the correct settings.

  1. Monitor the Replication Status: Finally, monitor the replication status to make sure that the new member is syncing data properly. You can use the following command to check the status:
rs.status()

This provides detailed information about each member, including their state, uptime, and replication lag. The new member should eventually reach a state of SECONDARY, indicating it has successfully joined the replica set and is in sync with the primary.

Note: When adding members to a replica set, consider the impact on the election process and read/write distribution. Adjusting member priorities and other settings may be necessary depending on your specific requirements and topology.

Adding a member to a MongoDB replica set expands its redundancy and capacity for read operations. It's a critical procedure for scaling and ensuring high availability of your MongoDB deployment.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.