【问题标题】:How to add a new node in mongo in an already initilized replicaset using pymongo?如何使用 pymongo 在已经初始化的副本集中在 mongo 中添加新节点?
【发布时间】:2018-03-20 12:37:23
【问题描述】:

我正在使用 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 在此副本集中添加一个新主机,但我无法这样做,因为这给了我一个副本集已经初始化的错误。我可以使用 mongo shell 来做到这一点

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

但我想在 python 中做同样的事情,但在 pymongo 的文档中没有找到任何内容。

【问题讨论】:

    标签: python mongodb amazon-web-services mongodb-query pymongo


    【解决方案1】:

    使用replSetReconfig复制命令。

    replSetReconfig 命令修改现有副本集的配置。您可以使用此命令添加和删除成员,以及更改现有成员上设置的选项。使用以下语法:

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多