Adding nodes to a MongoDB replica set using the Java driver

MongoDB console has a method for adding a replica to a replica set called rs.add. The Java driver doesn’t support this directly, but you can use the code from the mongo shell to implement add directly by running commands against the admin database.

rs.add = function (hostport, arb) {
    var cfg = hostport;
    var local = db.getSisterDB("local");
    assert(local.system.replset.count() <= 1, "error: local.system.replset has unexpected contents");
    var c = local.system.replset.findOne();
    assert(c, "no config object retrievable from local.system.replset");
    var max = 0;
    for (var i in c.members)
        if (c.members[i]._id > max) max = c.members[i]._id;
    if (isString(hostport)) {
        cfg = { _id: max + 1, host: hostport };
        if (arb)
            cfg.arbiterOnly = true;
    return this._runCmd({ replSetReconfig: c });

Leave a Reply

Your email address will not be published. Required fields are marked *