简体   繁体   中英

How to add a new node in mongo in an already initilized replicaset using pymongo?

I am creating a replicaset using pymongo with this code sample :

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 in future if my one node goes down and I want to add a new host in this replicaset again using pymongo , but I am unable to do so as this is giving me an error that replicaset already initilzed . I can do it with mongo shell using this

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

but I want to do the same in python and haven't found anything in the documentation of pymongo .

Use replSetReconfig Replication 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM