Navigation
This version of the documentation is archived and no longer supported.

Replica Set Commands

This reference collects documentation for all JavaScript methods for the mongo shell that support replica set functionality, as well as all database commands related to replication function.

See Replication, for a list of all replica set documentation.

JavaScript Methods

The following methods apply to replica sets. For a complete list of all methods, see JavaScript Methods.

rs.status()
Returns:A document with status information.

This output reflects the current status of the replica set, using data derived from the heartbeat packets sent by the other members of the replica set.

This method provides a wrapper around the replSetGetStatus database command.

See also

Replica Set Status Reference” for documentation of this output.

db.isMaster()

Returns a status document with fields that includes the ismaster field that reports if the current node is the primary node, as well as a report of a subset of current replica set configuration.

This function provides a wrapper around the database command isMaster

rs.initiate(configuration)
Parameters:
  • configuration – Optional. A document that specifies the configuration of a replica set. If not specified, MongoDB will use a default configuration.

Initiates a replica set. Optionally takes a configuration argument in the form of a document that holds the configuration of a replica set. Consider the following model of the most basic configuration for a 3-member replica set:

{
    _id : <setname>,
     members : [
         {_id : 0, host : <host0>},
         {_id : 1, host : <host1>},
         {_id : 2, host : <host2>},
     ]
}

This function provides a wrapper around the “replSetInitiatedatabase command.

rs.conf()
Returns:a document that contains the current replica set configuration object.
rs.config()

rs.config() is an alias of rs.conf().

rs.reconfig(configuration[, force])
Parameters:
  • configuration – A document that specifies the configuration of a replica set.
  • force – Optional. Specify { force: true } as the force parameter to force the replica set to accept the new configuration even if a majority of the members are not accessible. Use with caution, as this can lead to rollback situations.

Initializes a new replica set configuration. This function will disconnect the shell briefly and forces a reconnection as the replica set renegotiates which node will be primary. As a result, the shell will display an error even if this command succeeds.

rs.reconfig() provides a wrapper around the “replSetReconfigdatabase command.

rs.reconfig() overwrites the existing replica set configuration. Retrieve the current configuration object with rs.conf(), modify the configuration as needed and then use rs.reconfig() to submit the modified configuration object.

To reconfigure a replica set, use the following sequence of operations:

conf = rs.conf()

// modify conf to change configuration

rs.reconfig(conf)

If you want to force the reconfiguration if a majority of the set isn’t connected to the current member, or you’re issuing the command against a secondary, use the following form:

conf = rs.conf()

// modify conf to change configuration

rs.reconfig(conf, { force: true } )

Warning

Forcing a rs.reconfig() can lead to rollback situations and other difficult to recover from situations. Exercise caution when using this option.

rs.add(hostspec, arbiterOnly)

Specify one of the following forms:

Parameters:
  • host (string,document) – Either a string or a document. If a string, specifies a host (and optionally port-number) for a new host member for the replica set; MongoDB will add this host with the default configuration. If a document, specifies any attributes about a member of a replica set.
  • arbiterOnly (boolean) – Optional. If true, this host is an arbiter. If the second argument evaluates to true, as is the case with some documents, then this instance will become an arbiter.

Provides a simple method to add a member to an existing replica set. You can specify new hosts in one of two ways:

  1. as a “hostname” with an optional port number to use the default configuration as in the Add a Member to an Existing Replica Set example.
  2. as a configuration document, as in the Add a Member to an Existing Replica Set (Alternate Procedure) example.

This function will disconnect the shell briefly and forces a reconnection as the replica set renegotiates which node will be primary. As a result, the shell will display an error even if this command succeeds.

rs.add() provides a wrapper around some of the functionality of the “replSetReconfigdatabase command and the corresponding shell helper rs.reconfig(). See the Replica Set Configuration document for full documentation of all replica set configuration options.

Example

To add a mongod accessible on the default port 27017 running on the host mongodb3.example.net, use the following rs.add() invocation:

rs.add('mongodb3.example.net:27017')

If mongodb3.example.net is an arbiter, use the following form:

rs.add('mongodb3.example.net:27017', true)

To add mongodb3.example.net as a secondary-only member of set, use the following form of rs.add():

rs.add( { "_id": 3, "host": "mongodbd3.example.net:27017", "priority": 0 } )

Replace, 3 with the next unused _id value in the replica set. See rs.conf() to see the existing _id values in the replica set configuration document.

See the Replica Set Configuration and Replica Set Operation and Management documents for more information.

rs.addArb(hostname)
Parameters:
  • host (string) – Specifies a host (and optionally port-number) for an arbiter member for the replica set.

Adds a new arbiter to an existing replica set.

This function will disconnect the shell briefly and forces a reconnection as the replica set renegotiates which node will be primary. As a result, the shell will display an error even if this command succeeds.

rs.stepDown(seconds)
Parameters:
  • seconds (init) – Specify the duration of this operation. If not specified the command uses the default value of 60 seconds.
Returns:

disconnects shell.

Forces the current replica set member to step down as primary and then attempt to avoid election as primary for the designated number of seconds. Produces an error if the current node is not primary.

This function will disconnect the shell briefly and forces a reconnection as the replica set renegotiates which node will be primary. As a result, the shell will display an error even if this command succeeds.

rs.stepDown() provides a wrapper around the database command replSetStepDown.

rs.freeze(seconds)
Parameters:
  • seconds (init) – Specify the duration of this operation.

Forces the current node to become ineligible to become primary for the period specified.

rs.freeze() provides a wrapper around the database command replSetFreeze.

rs.remove(hostname)
Parameters:
  • hostname – Specify one of the existing hosts to remove from the current replica set.

Removes the node described by the hostname parameter from the current replica set. This function will disconnect the shell briefly and forces a reconnection as the replica set renegotiates which node will be primary. As a result, the shell will display an error even if this command succeeds.

Note

Before running the rs.remove() operation, you must shut down the replica set member that you’re removing.

Changed in version 2.2: This procedure is no longer required when using rs.remove(), but it remains good practice.

db.isMaster()

Returns a status document with fields that includes the ismaster field that reports if the current node is the primary node, as well as a report of a subset of current replica set configuration.

This function provides a wrapper around the database command isMaster

rs.help()

Returns a basic help text for all of the replication related shell functions.

rs.syncFrom()

New in version 2.2.

Provides a wrapper around the replSetSyncFrom, which allows administrators to configure the member of a replica set that the current member will pull data from. Specify the name of the member you want to replicate from in the form of [hostname]:[port].

See replSetSyncFrom for more details.

Database Commands

The following commands apply to replica sets. For a complete list of all commands, see Database Commands Quick Reference.

isMaster

The isMaster command provides a basic overview of the current replication configuration. MongoDB drivers and clients use this command to determine what kind of member they’re connected to and to discover additional members of a replica set. The db.isMaster() method provides a wrapper around this database command.

The command takes the following form:

{ isMaster: 1 }

This command returns a document containing the following fields:

isMaster.setname

The name of the current replica set, if applicable.

isMaster.ismaster

A boolean value that reports when this node is writable. If true, then the current node is either a primary in a replica set, a master in a master-slave configuration, or a standalone mongod.

isMaster.secondary

A boolean value that, when true, indicates that the current member is a secondary member of a replica set.

isMaster.hosts

An array of strings in the format of “[hostname]:[port]” listing all members of the replica set that are not “hidden”.

isMaster.arbiter

An array of strings in the format of “[hostname]:[port]” listing all members of the replica set that are arbiters

Only appears in the isMaster response for replica sets that have arbiter members.

isMaster.arbiterOnly

A boolean value that, when true indicates that the current instance is an arbiter.

arbiterOnly only appears in the isMaster response from arbiters.

isMaster.primary

The [hostname]:[port] for the current replica set primary, if applicable.

isMaster.me

The [hostname]:[port] of the node responding to this command.

isMaster.maxBsonObjectSize

The maximum permitted size of a BSON object in bytes for this mongod process. If not provided, clients should assume a max size of “4 * 1024 * 1024”.

isMaster.localTime

New in version 2.1.1.

Returns the local server time in UTC. This value is a ISOdate. You can use the toString() JavaScript method to convert this value to a local date string, as in the following example:

db.isMaster().localTime.toString();
resync

The resync command forces an out-of-date slave mongod instance to re-synchronize itself. Note that this command is relevant to master-slave replication only. It does not apply to replica sets.

Warning

This command obtains a global write lock and will block other operations until it has completed.

replSetFreeze

The replSetFreeze command prevents a replica set member from seeking election for the specified number of seconds. Use this command in conjunction with the replSetStepDown command to make a different node in the replica set a primary.

The replSetFreeze command uses the following syntax:

{ replSetFreeze: <seconds> }

If you want to unfreeze a replica set member before the specified number of seconds has elapsed, you can issue the command with a seconds value of 0:

{ replSetFreeze: 0 }

Restarting the mongod process also unfreezes a replica set member.

replSetFreeze is an administrative command, and you must issue the it against the admin database.

replSetGetStatus

The replSetGetStatus command returns the status of the replica set from the point of view of the current server. You must run the command against the admin database. The command has the following prototype format:

{ replSetGetStatus: 1 }

However, you can also run this command from the shell like so:

rs.status()
replSetInitiate

The replSetInitiate command initializes a new replica set. Use the following syntax:

{ replSetInitiate : <config_document> }

The <config_document> is a document that specifies the replica set’s configuration. For instance, here’s a config document for creating a simple 3-member replica set:

{
    _id : <setname>,
     members : [
         {_id : 0, host : <host0>},
         {_id : 1, host : <host1>},
         {_id : 2, host : <host2>},
     ]
}

A typical way of running this command is to assign the config document to a variable and then to pass the document to the rs.initiate() helper:

  config = {
      _id : "my_replica_set",
       members : [
           {_id : 0, host : "rs1.example.net:27017"},
           {_id : 1, host : "rs2.example.net:27017"},
           {_id : 2, host : "rs3.example.net", arbiterOnly: true},
       ]
  }

  rs.initiate(config)

Notice that omitting the port cause the host to use the default port
of 27017. Notice also that you can specify other options in the config
documents such as the ``arbiterOnly`` setting in this example.
replSetMaintenance

The replSetMaintenance admin command enables or disables the maintenance mode for a secondary member of a replica set.

The command has the following prototype form:

{ replSetMaintenance: <boolean> }

Consider the following behavior when running the replSetMaintenance command:

  • You cannot run the command on the Primary.
  • You must run the command against the admin database.
  • When enabled replSetMaintenance: 1, the member enters the RECOVERING state. While the secondary is RECOVERING:
    • The member is not accessible for read operations.
    • The member continues to sync its oplog from the Primary.
replSetReconfig

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:

{ replSetReconfig: <new_config_document>, force: false }

You may also run the command using the shell’s rs.reconfig() method.

Be aware of the following replSetReconfig behaviors:

  • You must issue this command against the admin database of the current primary member of the replica set.

  • You can optionally force the replica set to accept the new configuration by specifying force: true. Use this option if the current member is not primary or if a majority of the members of the set are not accessible.

    Warning

    Forcing the replSetReconfig command can lead to a rollback situation. Use with caution.

    Use the force option to restore a replica set to new servers with different hostnames. This works even if the set members already have a copy of the data.

  • A majority of the set’s members must be operational for the changes to propagate properly.

  • This command can cause downtime as the set renegotiates primary-status. Typically this is 10-20 seconds, but could be as long as a minute or more. Therefore, you should attempt to reconfigure only during scheduled maintenance periods.

  • In some cases, replSetReconfig forces the current primary to step down, initiating an election for primary among the members of the replica set. When this happens, the set will drop all current connections.

Note

replSetReconfig obtains a special mutually exclusive lock to prevent more than one replSetReconfig operation from occurring at the same time.

replSetSyncFrom

New in version 2.2.

Options:
  • host – Specifies the name and port number of the replica set member that this member replicates from. Use the [hostname]:[port] form.

replSetSyncFrom allows you to explicitly configure which host the current mongod will poll oplog entries from. This operation may be useful for testing different patterns and in situations where a set member is not replicating from the host you want. The member to replicate from must be a valid source for data in the set.

A member cannot replicate from:

  • itself.
  • an arbiter, because arbiters do not hold data.
  • a member that does not build indexes.
  • an unreachable member.
  • a mongod instance that is not a member of the same replica set.

If you attempt to replicate from a member that is more than 10 seconds behind the current member, mongod will return and log a warning, but it still will replicate from the member that is behind.

If you run rs.syncFrom() during initial sync, MongoDB produces no error messages, but the sync target will not change until after the initial sync operation.

The command has the following prototype form:

{ replSetSyncFrom: "[hostname]:[port]" }

To run the command in the mongo shell, use the following invocation:

db.adminCommand( { replSetSyncFrom: "[hostname]:[port]" } )

You may also use the rs.syncFrom() helper in the mongo shell, in an operation with the following form:

rs.syncFrom("[hostname]:[port]")

Note

replSetSyncFrom and rs.syncFrom() provide a temporary override of default behavior. If:

  • the mongod instance restarts or
  • the connection to the sync target closes;

then, the mongod instance will revert to the default sync logic and target.