如何使用pymongo在已经初始化的复制集中添加一个新节点?

2024-10-03 11:20:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pymongo创建一个复制集,代码示例如下:

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)

现在,如果我的一个节点坏了,我想再次使用pymongo在这个复制集中添加一个新主机,但是我不能这样做,因为这会给我一个复制集已经初始化的错误。我可以用mongoshell使用这个

^{pr2}$

但是我想在python中做同样的事情,但是在pymongo的文档中没有发现任何东西。在


Tags: 代码clientidconfighost示例dbadmin
1条回答
网友
1楼 · 发布于 2024-10-03 11:20:46

使用^{}复制命令。在

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)

相关问题 更多 >