OPTIONS
翻译或纠错本页面

移除复制集的节点

移除 replica set 中的节点可以使用下列方式。

使用 rs.remove() 来移除节点

  1. 关闭我们想要移除的 mongod 实例,可以通过在 mongo 的窗口中执行 db.shutdownServer() 来关闭。

  2. 连接到复制集现在的 primary 。我们可以连接到任意一个复制集节点并执行 db.isMaster() 来确认是否为主节点。

  3. 通过 rs.remove() 来移除节点,以下是列子:

    rs.remove("mongod3.example.net:27017")
    rs.remove("mongod3.example.net")
    

    复制集将会短暂的关闭连接并进入选举,选举出一个新的主节点。接口将会自动重连。接口将会报错 DBClientCursor::init call() failed 即使删除节点成功了。

通过 rs.reconfig() 来移除节点

我们可以通过修改 replica set configuration document 来移除节点。

  1. 关闭我们想要移除的 mongod 实例,可以通过在 mongo 的窗口中执行 db.shutdownServer() 来关闭。

  2. 连接到复制集现在的 primary 。我们可以连接到任意一个复制集节点并执行 db.isMaster() 来确认是否为主节点。

  3. 使用 rs.conf() 来查看现在的复制集配置,并记住我们需要移除的节点的 members 数组的位置。

    例子

    在下列的配置中 mongod_C.example.net 的位置是 2

    {
        "_id" : "rs",
        "version" : 7,
        "members" : [
            {
                "_id" : 0,
                "host" : "mongod_A.example.net:27017"
            },
            {
                "_id" : 1,
                "host" : "mongod_B.example.net:27017"
            },
            {
                "_id" : 2,
                "host" : "mongod_C.example.net:27017"
            }
        ]
    }
    
  4. 将现在的的配置赋值给 cfg

    cfg = rs.conf()
    
  5. 修改 cfg 来移除节点。

    例子

    通过如下的命令来移除节点 mongod_C.example.net:27017

    cfg.members.splice(2,1)
    
  6. 通过如下命令将新的配置覆盖应用在复制集用:

    rs.reconfig(cfg)
    

    As a result of rs.reconfig() the shell will disconnect while the replica set renegotiates which member is primary. The shell displays a DBClientCursor::init call() failed error even though the command succeeds, and will automatically reconnected.

  7. 通过 rs.conf() 命令来再确认新的配置。

    输出将会是如下形式的:

    {
        "_id" : "rs",
        "version" : 8,
        "members" : [
            {
                "_id" : 0,
                "host" : "mongod_A.example.net:27017"
            },
            {
                "_id" : 1,
                "host" : "mongod_B.example.net:27017"
            }
        ]
    }