Python – How can I use pymongo to add a new node to an already initialized replica set?

How can I use pymongo to add a new node to an already initialized replica set?… here is a solution to the problem.

How can I use pymongo to add a new node to an already initialized replica set?

I’m creating a replica set using pymongo with this code example:

client = MongoClient(allIps[0]+':27017',username='mongo-admin', password='${mongo_password}', authSource='admin')
    db=client.admin
    config = {'_id': 'Harmony-demo', 'members': [
        {'_id': 0, 'host': allIps[0]+':27017'},
        {'_id': 1, 'host': allIps[1]+':27017'},
        {'_id': 2, 'host': allIps[2]+':27017'}]}
    db.command("replSetInitiate",config)

Now, if one of my nodes fails, and I want to use pymongo again to add a new host to this replicaset, but I can’t do that because that would give me an error that the replicaset has already been initialized. I can use this with the mongo shell

rs.add( { host: "mongodbd4.example.net:27017" } )

But I want to do the same thing in python and didn’t find anything in the pymongo’s docs.

Solution

Use replSetReconfig copy command.

The replSetReconfig command modifies the configuration of an existing replica set. You can use this command to add and remove members, and to alter the options set on existing members. Use the following syntax:

result = db.command('replSetGetConfig')
config = result['config']
max_member_id = max(member['_id'] for member in config['members'])

config['members'].append(
    {'_id': max_member_id + 1, 'host': 'mongodbd4.example.net:27017'}
)
config['version'] += 1 # update config version 
db.command('replSetReconfig', config)

Related Problems and Solutions