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.
The following methods apply to replica sets. For a complete list of all methods, see mongo Shell Methods.
| 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.
| Returns: | A document that describes the role of the mongod instance. |
|---|
If the mongod is a member of a replica set, then the ismaster and secondary fields report if the instance is the primary or if it is a secondary member of the replica set.
| Parameters: |
|
|---|
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 “replSetInitiate” database command.
| Returns: | a document that contains the current replica set configuration object. |
|---|
rs.config() is an alias of rs.conf().
Initializes a new replica set configuration. Disconnects 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.
| Parameter | Type | Description |
|---|---|---|
| configuration | document | A document that specifies the configuration of a replica set. |
| force | document | Optional. “If set as { force: true }, this forces 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 term:rollback situations.” |
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.
rs.reconfig() provides a wrapper around the “replSetReconfig” database command.
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 is not connected to the current member, or you are 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.
See also
Adds a member to a replica set.
| Parameter | Type | Description |
|---|---|---|
| host | string or 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. |
You may specify new hosts in one of two ways:
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 “replSetReconfig” database command and the corresponding shell helper rs.reconfig(). See the Replica Set Configuration document for full documentation of all replica set configuration options.
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 Administration documents for more information.
| Parameters: |
|
|---|
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.
| Parameters: |
|
|---|---|
| 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.
| Parameters: |
|
|---|
Forces the current node to become ineligible to become primary for the period specified.
rs.freeze() provides a wrapper around the database command replSetFreeze.
| Parameters: |
|
|---|
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.
Provides a shorthand for the following operation:
db.getMongo().setSlaveOk()
This allows the current connection to allow read operations to run on secondary nodes. See the readPref() method for more fine-grained control over read preference in the mongo shell.
| Returns: | A document that describes the role of the mongod instance. |
|---|
If the mongod is a member of a replica set, then the ismaster and secondary fields report if the instance is the primary or if it is a secondary member of the replica set.
Returns a basic help text for all of the replication related shell functions.
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.
The following commands apply to replica sets. For a complete list of all commands, see Database Commands.
isMaster returns a document that describes the role of the mongod instance.
If the instance is a member of a replica set, then isMaster returns a subset of the replica set configuration and status including whether or not the instance is the primary of the replica set.
When sent to a mongod instance that is not a member of a replica set, isMaster returns a subset of this information.
MongoDB drivers and clients use isMaster to determine the state of the replica set members and to discover additional members of a replica set.
The db.isMaster() method in the mongo shell provides a wrapper around isMaster.
The command takes the following form:
{ isMaster: 1 }
See also
The following isMaster fields are common across all roles:
A boolean value that reports when this node is writable. If true, then this instance is a primary in a replica set, or a master in a master-slave configuration, or a mongos instance, or a standalone mongod.
This field will be false if the instance is a secondary member of a replica set or if the member is an arbiter of a replica set.
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 contains these fields when returned by a member of a replica set:
The name of the current :replica set.
A boolean value that, when true, indicates if the mongod is a secondary member of a replica set.
An array of strings in the format of "[hostname]:[port]" that lists all members of the replica set that are neither hidden, passive, nor arbiters.
Drivers use this array and the isMaster.passives to determine which members to read from.
An array of strings in the format of "[hostname]:[port]" listing all members of the replica set which have a priority of 0.
This field only appears if there is at least one member with a priority of 0.
Drivers use this array and the isMaster.hosts to determine which members to read from.
An array of strings in the format of "[hostname]:[port]" listing all members of the replica set that are arbiters.
This field only appears if there is at least one arbiter in the replica set.
A string in the format of "[hostname]:[port]" listing the current primary member of the replica set.
A boolean value that , when true, indicates that the current instance is an arbiter. The arbiterOnly field is only present, if the instance is an arbiter.
A boolean value that, when true, indicates that the current instance is hidden. The passive field is only present for hidden members.
A boolean value that, when true, indicates that the current instance is hidden. The hidden field is only present for hidden members.
A document that lists any tags assigned to this member. This field is only present if there are tags assigned to the member. See Configure Replica Set Tag Sets for more information.
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.
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 it against the admin database.
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 }
The value specified does not affect the output of the command. Data provided by this command derives from data included in heartbeats sent to the current instance by other members of the replica set. Because of the frequency of heartbeats, these data can be several seconds out of date.
You can also access this functionality through the rs.status() helper in the mongo shell.
The mongod must have replication enabled and be a member of a replica set for the for replSetGetStatus to return successfully.
The set value is the name of the replica set, configured in the replSet setting. This is the same value as _id in rs.conf().
The value of the date field is an ISODate of the current time, according to the current server. Compare this to the value of the lastHeartbeat to find the operational lag between the current host and the other hosts in the set.
The value of myState reflects state of the current replica set member. An integer between 0 and 10 represents the state of the member. These integers map to states, as described in the following table:
| Number | Name | State |
|---|---|---|
| 0 | STARTUP | Start up, phase 1 (parsing configuration.) |
| 1 | PRIMARY | Primary. |
| 2 | SECONDARY | Secondary. |
| 3 | RECOVERING | Member is recovering (initial sync, post-rollback, stale members.) |
| 4 | FATAL | Member has encountered an unrecoverable error. |
| 5 | STARTUP2 | Start up, phase 2 (forking threads.) |
| 6 | UNKNOWN | Unknown (the set has never connected to the member.) |
| 7 | ARBITER | Member is an arbiter. |
| 8 | DOWN | Member is not accessible to the set. |
| 9 | ROLLBACK | Member is rolling back data. See rollback. |
| 10 | SHUNNED | Member has been removed from replica set. |
The members field holds an array that contains a document for every member in the replica set.
The name field holds the name of the server.
The self field is only included in the document for the current mongod instance in the members array. It’s value is true.
This field contains the most recent error or status message received from the member. This field may be empty (e.g. "") in some cases.
The health value is only present for the other members of the replica set (i.e. not the member that returns rs.status.) This field conveys if the member is up (i.e. 1) or down (i.e. 0.)
The value of the state reflects state of this replica set member. An integer between 0 and 10 represents the state of the member. These integers map to states, as described in the following table:
| Number | Name | State |
|---|---|---|
| 0 | STARTUP | Start up, phase 1 (parsing configuration.) |
| 1 | PRIMARY | Primary. |
| 2 | SECONDARY | Secondary. |
| 3 | RECOVERING | Member is recovering (initial sync, post-rollback, stale members.) |
| 4 | FATAL | Member has encountered an unrecoverable error. |
| 5 | STARTUP2 | Start up, phase 2 (forking threads.) |
| 6 | UNKNOWN | Unknown (the set has never connected to the member.) |
| 7 | ARBITER | Member is an arbiter. |
| 8 | DOWN | Member is not accessible to the set. |
| 9 | ROLLBACK | Member is rolling back data. See rollback. |
| 10 | SHUNNED | Member has been removed from replica set. |
The uptime field holds a value that reflects the number of seconds that this member has been online.
This value does not appear for the member that returns the rs.status() data.
A document that contains information regarding the last operation from the operation log that this member has applied.
A 32-bit timestamp of the last operation applied to this member of the replica set from the oplog.
An incremented field, which reflects the number of operations in since the last time stamp. This value only increases if there is more than one operation per second.
An ISODate formatted date string that reflects the last entry from the oplog that this member applied. If this differs significantly from lastHeartbeat this member is either experiencing “replication lag” or there have not been any new operations since the last update. Compare members.optimeDate between all of the members of the set.
The lastHeartbeat value provides an ISODate formatted date of the last heartbeat received from this member. Compare this value to the value of the date field to track latency between these members.
This value does not appear for the member that returns the rs.status() data.
The pingMS represents the number of milliseconds (ms) that a round-trip packet takes to travel between the remote member and the local instance.
This value does not appear for the member that returns the rs.status() data.
The syncingTo field is only present on the output of rs.status() on secondary and recovering members, and holds the hostname of the member from which this instance is syncing.
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.
See also
“Replica Set Configuration,” “Replica Set Administration,” and “Replica Set Reconfiguration.”
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:
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.
New in version 2.2.
| Options: |
|
|---|
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:
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,
the connection to the sync target closes, or
Changed in version 2.4: The sync target falls more than 30 seconds behind another member of the replica set;
then, the mongod instance will revert to the default sync logic and target.