Add, Edit or Remove Host from MongoDB ReplicaSet -

Add, Edit or Remove Host from MongoDB ReplicaSet

There are 2 ways to add or remove host from mongodb running replica set

  • without downtime
  • with downtime

If your application is not yet live, or you can afford downtime, you should go with downtime approach, as it occurs less risk and is more easy to achieve

In this tutorial we will see how to add/edit host using downtime method, which is faster to complete

  • to add host using downtime method

Add, Edit or Remove Host from Replica Set

1. Stop all replica-set instances

  • Login to all instances and stop mongodb
sudo systemctl restart mongod
sudo systemctl status mongod

2. Start MongoDB temporarily

  • You need to start MongoDB again without a replica set option, so it should run as standalone application
  • While doing this, you can also change MongoDB’s port number so accidentally any client doesn’t connect to mongo and write some data which can’t be replicated
  • Here, make sure mongodb that you are connecting with is taking exact directory path as replica set’s data path. If default path is not set, while running mentioned command add --db-path /path/to/directory as well
sudo mongod --port 37017
sudo systemctl status mongod

3. Add instance

  • If you are adding any instance in the replica set, follow these steps to launch an instance, install MongoDB and add replica set configuration as required
  • For edit in hostname, Do changes to pointing of IP or hostname and keep it handy with you for next steps

4. Log into MongoDB and change replication configuration

  • Connect to each mongodb using mongosh or mongo client and perform below mentioned operations

Here, I’m editing one of the hostname from my current configuration and applying those changes for whole replica set.

You need to perform this operation in each replica set machine

mongo --port 37017
# change to mongosh 

use local
cfg = db.system.replset.findOne( { "_id": "poc-ic" } )

cfg.members[0].host = ""

cfg.members[1].host = ""

cfg.members[2].host = ""

db.system.replset.update( { "_id": "poc-ic" } , cfg )
# here command is changed with new mongo update, add it from notes 

5. Start MongoDB with Changes

After getting success, in updating changes in all machines of replica set, now we need to stop mongo db again and restart it with correct port and replica set configuration

sudo systemctl stop mongod
sudo systemctl start mongod
sudo systemctl status mongod

6. Verify your changes

  • Connect to any machine of mongodb replica and verify replication status
sudo mongod -u -p
#complete the command


Read More:

How to create MongoDB replica set clusterHow to: Run MySQL and PHPMyAdmin through Docker
15 Most Basic Linux Commands Every System Admin And DevOps Must KnowHow To Issue A Free SSL Certificate For Your Site Using Letโ€™s Encrypt

Leave a Comment