Introducing Dragonfly Cloud! Learn More

Question: How do you join a replica set in MongoDB?

Answer

Joining a node to a MongoDB replica set involves adding the node as a member of an existing replica set. To accomplish this, you'll need to follow these steps:

  1. Prepare the New Node: Install MongoDB on the new server if it's not already installed. Ensure that the version of MongoDB matches that of the existing replica set members.

  2. Configure MongoDB for Replication: On the new node, edit the MongoDB configuration file (typically mongod.conf) to enable replication and specify the replica set name. For example:

    replication: replSetName: \"rs0\"

    Replace "rs0" with your replica set's name. Restart the MongoDB service after making these changes.

  3. Add the New Node to the Replica Set: From one of the existing members of the replica set, connect to the MongoDB shell and use the rs.add() command to add the new node. You need to provide the hostname and, optionally, the port number of the new node:

    rs.add(\"newNodeHostname:27017\")

    Replace \"newNodeHostname:27017\" with the actual hostname and port of the new node. If MongoDB is running on the default port (27017), you can omit the port number.

  4. Verify the Replica Set Configuration: After adding the new node, you can check the status of the replica set to ensure that the new node has been successfully added and is in sync with the other members:

    rs.status()

This process adds the new node as a data-bearing node by default. If you intend to add the node as an arbiter (which does not hold data and only participates in elections for primary), you should use rs.addArb() instead of rs.add().

Note: When joining a node to a replica set, ensure that network connectivity between all members is properly configured and that necessary firewall rules are in place to allow communication on the required ports (default is 27017). Moreover, the replica set configuration change must propagate to all existing members, so the addition of the new node might not be instantaneous.

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

Start building today 

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