MongoDB1.6的版本中,向Replica Set中增加成员很简单,如下:

#增加新的成员
rs.add("192.168.x,210:10000");
#增加新的选举成员
rs.addArb("192.168.x,216:10001");

这样配置好,Mongo会自动把数据同步到新的成员上

1.6版本中没有提供remove成员的命令,据说在1.7版本中有这个命令

不过,我们可以通过replSetReconfig来完成此操作

下面我们去掉set中一个成员,并增加一个新的成员,操作如下:

#在remove的成员上停掉MongoDB服务
kill -2 `cat /opt/mongodb_data/mongod.lock`
#将老成员的数据data文件scp到新服务器上,为了加快rs_sync的过程
scp suv.* 10.x.x.x:/pvdata/
#在新成员上启动MongoDB服务
/usr/local/mongodb/bin/mongod --fork --shardsvr --port 10000 --replSet set2 --dbpath /pvdata/mongodb_data  --logpath /pvdata/mongodb_log/mongod.log --logappend
#在该set的Master成员上执行命令
config = {_id: 'set2', members: [
        {_id: 0, host: '192.168.x,218:10000'},
        {_id: 1, host: '10.x.x.x:10000'},
        {_id: 2, host: '192.168.x,216:10001', arbiterOnly: true}
    ]}
    use local
    old_config = db.system.replset.findOne();
    #注意需要设置新config的versin,否则会报错version number wrong
    config.version = old_config.version + 1;
    use admin
    db.runCommand({ replSetReconfig : config })

这样就完成了对Replica Set的重新配置,移走了一台旧服务器,并增加了15.39的新服务器

我们查看新服务器mongod.log,可以看到:

Wed Oct 27 14:24:19 done allocating datafile /pvdata/mongodb_data/local.ns, size: 16MB,  took 0.049 secs
...
Wed Oct 27 17:55:12 [rs_sync] replSet initialSyncOplogApplication 66500000
Wed Oct 27 17:58:02 [rs_sync] replSet initial sync finishing up
Wed Oct 27 17:58:02 [rs_sync] replSet set minValid=4cc7f49a:7b
Wed Oct 27 17:58:02 [rs_sync] building new index on { _id: 1 } for local.replset.minvalid
Wed Oct 27 17:58:02 [rs_sync] done for 0 records 0.052secs
Wed Oct 27 17:58:02 [rs_sync] replSet initial sync done
Wed Oct 27 17:58:04 [rs_sync] replSet SECONDARY

最后,说明新的Server已经sync完成,并作为secondary成功启动了

我们用rs.status()也能看到新的set的状态:

{
        "set" : "set2",
        "date" : "Wed Oct 27 2010 17:57:39 GMT+0800 (CST)",
        "myState" : 1,
        "members" : [
                {
                        "_id" : 0,
                        "name" : "zjm-hadoop-slave218:10000",
                        "health" : 1,
                        "state" : 1,
                        "self" : true
                },
                {
                        "_id" : 1,
                        "name" : "10.x.x.x.x:10000",
                        "health" : 1,
                        "state" : 3,
                        "uptime" : 1231,
                        "lastHeartbeat" : "Wed Oct 27 2010 17:57:39 GMT+0800 (CST)"
                },
                {
                        "_id" : 2,
                        "name" : "192.168.x,216:10001",
                        "health" : 1,
                        "state" : 7,
                        "uptime" : 1237,
                        "lastHeartbeat" : "Wed Oct 27 2010 17:57:39 GMT+0800 (CST)"
                }
        ],
        "ok" : 1
}