rs.reconfig()

On this page本页内容

Definition定义

rs.reconfig( configuration, { options } )

Reconfigures an existing replica set, overwriting the existing replica set configuration. 重新配置现有副本集,覆盖现有副本集配置。To run the method, you must connect to the primary of the replica set.要运行该方法,必须连接到副本集的primary

The rs.reconfig() method has the following syntax:rs.reconfig()方法具有以下语法:

rs.reconfig(
  <configuration>,
  {
    "force" : <boolean>,
    "maxTimeMS" : <int>
  }
)
Parameter参数Type类型Description描述

configuration

documentA document that specifies the configuration of a replica set.指定副本集配置的文档

force

boolean

Optional可选

Specify true to force the available replica set members to accept the new configuration. 指定true可强制可用副本集成员接受新配置。Defaults to false.默认为false

Force reconfiguration can result in unexpected or undesired behavior, including rollback of "majority" committed writes.强制重新配置可能导致意外或不期望的行为,包括回滚"majority"提交的写入。

maxTimeMS

integer

Optional可选

Specifies a cumulative time limit in milliseconds for processing the rs.reconfig() operation. 指定处理rs.reconfig()操作的累积时间限制(毫秒)。By default, rs.reconfig() waits indefinitely for the replica configuration to propagate to a majority of replica set members.默认情况下,rs.reconfig()无限期地等待副本配置传播到大多数副本集成员。

New in version 4.4.在版本4.4中新增

To reconfigure an existing replica set, first retrieve the current configuration with rs.conf(), modify the configuration document as needed, and then pass the modified document to rs.reconfig().要重新配置现有副本集,首先使用rs.conf()检索当前配置,根据需要修改配置文档,然后将修改后的文档传递给rs.reconfig()

rs.reconfig() provides a wrapper around the replSetReconfig command.提供了replSetReconfig命令的包装。

The force parameter allows a reconfiguration command to be issued to a non-primary node.force参数允许向非主节点发出重新配置命令。

Behavior行为

Global Write Concern全球写入问题

Starting in MongoDB 5.0, you must explicitly set the global default write concern before attempting to reconfigure a replica set with a configuration that would change the implicit default write concern. 从MongoDB 5.0开始,您必须显式设置全局默认写入关注点,然后才能尝试使用将更改隐式默认写入问题的配置重新配置副本集To set the global default write concern, use the setDefaultRWConcern command.要设置全局默认写入问题,请使用setDefaultRWConcern命令。

term Replica Configuration Field副本配置字段

MongoDB 4.4 adds the term field to the replica set configuration document. MongoDB 4.4将term字段添加到副本集配置文档中。The term field is set by the primary replica set member. term字段由主副本集成员设置。The primary ignores the term field if set explicitly in the rs.reconfig() operation.如果在rs.reconfig()操作中显式设置了term字段,则primary将忽略该字段。

Reconfiguration Can Add or Remove No More than One Voting Member at a Time重新配置一次只能添加或删除一个以上有投票权的成员

Starting in MongoDB 4.4, rs.reconfig() by default allows adding or removing no more than 1 voting member at a time. 从MongoDB 4.4开始,rs.reconfig()默认允许一次添加或删除不超过1voting成员。For example, a new configuration can make at most one of the following changes to the cluster membership:例如,新配置最多可以对群集membership进行以下更改之一:

  • Adding a new voting replica set member.添加新的投票副本集成员。
  • Removing an existing voting replica set member.正在删除现有投票副本集成员。
  • Modifying the votes for an existing replica set member.修改现有副本集成员的votes

To add or remove multiple voting members, issue a series of rs.reconfig() operations to add or remove one member at a time.要添加或删除多个投票成员,请执行一系列rs.reconfig()操作,一次添加或删除一个成员。

Issuing a force reconfiguration immediately installs the new configuration even if it adds or removes multiple voting members. 发出强制重新配置会立即安装新配置,即使它添加或删除了多个投票成员。Force reconfiguration can cause unexpected behavior, such as the rollback of "majority" committed write operations.强制重新配置可能会导致意外行为,例如回滚"majority"提交的写入操作。

Reconfiguration Waits Until a Majority of Members Install the Replica Configuration重新配置等待大多数成员安装副本配置

Starting in MongoDB 4.4, rs.reconfig() waits until a majority of voting replica set members install the new replica configuration before returning success. 从MongoDB 4.4开始,rs.reconfig()等待,直到大多数有投票权的副本集成员安装了新的副本配置,然后返回成功。A voting member is any replica set member where members[n].votes is 1, including arbiters.投票成员是members[n].votes1的任何副本集成员,包括仲裁员。

Replica set members propagate their replica configuration via heartbeats. 副本集成员通过心跳传播其副本配置。Whenever a member learns of a configuration with a higher version and term, it installs the new configuration. 每当成员了解到具有更高versionterm的配置时,就会安装新的配置。The reconfiguration process has two distinct 'waiting' phases:重新配置过程有两个不同的“等待”阶段:

1) Wait for the current configuration to be committed before installing the new configuration.在安装新配置之前,请等待提交当前配置。

The "current" configuration refers to the replica configuration in use by the primary at the time rs.reconfig() is issued.“当前”配置是指发出rs.reconfig()时主服务器正在使用的副本配置。

A configuration is committed when:在以下情况下提交配置:

  • A majority of voting replica set members have installed the current configuration, and大多数投票副本集成员已安装当前配置,并且
  • All writes which were "majority" committed in the previous configuration have also replicated to a majority in the current configuration.在先前配置中提交的所有"majority"写入也已复制到当前配置中的多数。

Typically, the current configuration has already been installed on a majority of voting replica set members. 通常,当前配置已安装在大多数投票副本集成员上。However, the majority committed writes in the previous configuration may not all be committed in the current configuration. 但是,在以前的配置中提交的大多数写入可能不会全部在当前配置中提交。Delayed members or members that are lagging behind the primary can increase the time spent in this phase.延迟成员落后于primary的成员可能会增加此阶段的时间。

If the operation was issued with a maxTimeMS limit andthe operation exceeds the limit while waiting, the operation returns an error and discard the new configuration. 如果发出的操作具有maxTimeMS限制,并且该操作在等待时超出限制,则该操作将返回错误并放弃新配置。The limit is cumulative and does not reset after proceeding to the next phase.该限制是累积的,在进入下一阶段后不会重置。

2) Wait for a majority of voting members in the new configuration to install the new configuration.等待新配置中的大多数投票成员安装新配置。

The "new" configuration refers to the replica configuration specified to rs.reconfig().“新”配置指的是为rs.reconfig()指定的副本配置。

The primary installs and begins using the new replica configuration before propagating the configuration to the remaining replica set members. 主服务器安装并开始使用新的副本配置,然后将配置传播到其余副本集成员。The operation only waits for a majority of voting members to install the new configuration, and does not require waiting for the new configuration to be committed.该操作仅等待大多数投票成员安装新配置,而不需要等待提交新配置。

If the operation was issued with a maxTimeMS limit and the operation exceeds the limit while waiting, the operation returns an error but continues using and propagating the new configuration.如果该操作是以maxTimeMS限制发出的,并且该操作在等待时超出了限制,则该操作将返回错误,但会继续使用和传播新配置。

Issuing a force reconfiguration immediately installs the new configuration regardless of the commitment status of the previous configuration. 发出强制重新配置将立即安装新配置,而不管先前配置的承诺状态如何。Force reconfiguration can cause unexpected behavior, such as the rollback of "majority" committed write operations.强制重新配置可能会导致意外行为,例如回滚"majority"提交的写入操作。

To check the commitment status of the current replica configuration, issue replSetGetConfig with the commitmentStatus parameter on the replica set primary.要检查当前副本配置的提交状态,请在副本集主服务器上使用commitmentStatus参数发出replSetGetConfig

Access Control访问控制

To run the method on deployments that enforce access control, the user must have replSetConfigure privilege action on the cluster resource. 要在强制访问控制的部署上运行该方法,用户必须对群集资源具有replSetConfigure权限操作。The clusterManager built-in role, available in the admin database, provides the required privileges for this command.admin数据库中提供的clusterManager内置角色提供了此命令所需的权限。

Locking Behavior锁定行为

rs.reconfig() obtains a special mutually exclusive lock to prevent more than one rs.reconfig() operation from occurring at the same time.获取一个特殊的互斥锁,以防止同时发生多个rs.reconfig()操作。

Mixed Version Replica Set混合版本副本集

Warning警告

Avoid reconfiguring replica sets that contain members of different MongoDB versions as validation rules may differ across MongoDB versions.避免重新配置包含不同MongoDB版本成员的副本集,因为验证规则可能因MongoDB的版本而异。

Availability可用性

The rs.reconfig() shell method can trigger the current primary to step down in some situations. 在某些情况下,rs.reconfig()shell方法可以触发当前主进程下移。Primary step-down triggers an election to select a new primary:初选降级触发选举以选择新的primary

  • Starting in MongoDB 4.2, when the primary steps down, it no longer closes all client connections and writes that were in progress are killed. 从MongoDB 4.2开始,当主服务器停止运行时,它不再关闭所有客户端连接,正在进行的写入将被终止。For details, see Behavior.有关详细信息,请参阅行为
  • In MongoDB 4.0 and earlier, when the primary steps down, it closes all client connections.在MongoDB 4.0及更早版本中,当主服务器关闭时,它会关闭所有客户端连接。

The median time before a cluster elects a new primary should not typically exceed 12 seconds, assuming default replica configuration settings. 假设默认的复制副本配置设置,群集选择新主节点之前的中间时间通常不应超过12秒。This includes time required to mark the primary as unavailable and call and complete an election. 这包括将初选标记为不可用以及召集并完成选举所需的时间。You can tune this time period by modifying the settings.electionTimeoutMillis replication configuration option. 您可以通过修改设置settings.electionTimeoutMillis复制配置选项来调整此时间段。Factors such as network latency may extend the time required for replica set elections to complete, which in turn affects the amount of time your cluster may operate without a primary. 网络延迟等因素可能会延长完成副本集选择所需的时间,这反过来会影响集群在没有主节点的情况下运行的时间。These factors are dependent on your particular cluster architecture.这些因素取决于您的特定集群体系结构。

During the election process, the cluster cannot accept write operations until it elects the new primary.在选择过程中,群集在选择新的主节点之前无法接受写入操作。

Your application connection logic should include tolerance for automatic failovers and the subsequent elections. 您的应用程序连接逻辑应包括自动故障切换和后续选择的容差。Starting in MongoDB 3.6, MongoDB drivers can detect the loss of the primary and automatically retry certain write operations a single time, providing additional built-in handling of automatic failovers and elections:从MongoDB 3.6开始,MongoDB驱动程序可以检测到主数据库的丢失,并在一次内自动重试某些写入操作,从而提供自动故障切换和选择的额外内置处理:

  • MongoDB 4.2+ compatible drivers enable retryable writes by defaultMongoDB 4.2+兼容驱动程序默认启用可重试写入
  • MongoDB 4.0 and 3.6-compatible drivers must explicitly enable retryable writes by including retryWrites=true in the connection string.MongoDB 4.0和3.6兼容驱动程序必须通过在连接字符串中包含retryWrites=true来显式启用可重试写入。

To further reduce potential impact to a production cluster, reconfigure only during scheduled maintenance periods.为了进一步减少对生产集群的潜在影响,请仅在计划的维护期间重新配置。

{ force: true }

Warning警告

Using rs.reconfig() with { force: true } can lead to rollback of majority-committed writes. rs.reconfig(){ force: true }一起使用会导致大多数提交写入的回滚。Exercise caution when using this option.使用此选项时请小心。

Member Priority and Votes成员优先权和投票权

Changed in version 3.2.在版本3.2中更改

Drop Outgoing Connections After Removing a Member删除成员后删除传出连接

Using rs.reconfig() to remove a replica set member does not automatically drop open outgoing connections from other replica set members to the removed member.使用rs.reconfig()删除副本集成员不会自动放弃从其他副本集成员到已删除成员的开放传出连接。

By default, replica set members wait for 5 minutes before dropping connections to the removed member. 默认情况下,副本集成员会等待5分钟,然后再断开与已删除成员的连接。In sharded replica sets, you can modify this timeout using the ShardingTaskExecutorPoolHostTimeoutMS server parameter.在分片副本集中,可以使用ShardingTaskExecutorPoolHostTimeoutMS服务器参数修改此超时。

New in version 4.2.在版本4.2中新增 To immediately drop all outgoing connections from the replica set to the removed member, run the dropConnections administrative command on each remaining member on the replica set:要立即删除从副本集到已删除成员的所有传出连接,请对副本集上的每个剩余成员运行dropConnections管理命令:

db.adminCommand(
  {
    "dropConnections" : 1,
    "hostAndPort" : [
      "<hostname>:<port>"
    ]
  }
)

Replace <hostname> and <port> with those of the removed member.<hostname><port>替换为已删除成员的名称。

Automatic Reconfiguration for New Voting Replica Set Members新投票副本集成员的自动重新配置

Starting in MongoDB 5.0, a newly added secondary does not count as a voting member and cannot be elected until it has reached the SECONDARY state.从MongoDB 5.0开始,新添加的次要成员不算作投票成员,在达到SECONDARY状态之前不能当选。

When a new voting node is added to a replica set, replSetReconfig will internally add a newlyAdded field to the node's configuration. 当一个新的投票节点被添加到副本集中时,replSetReconfig将在内部向节点的配置中添加一个newlyAdded字段。Nodes with the newlyAdded field do not count towards the current number of voting nodes. 具有newlyAdded字段的节点不计入当前投票节点数。When initial sync completes and the node reaches SECONDARY state, the newlyAdded field is automatically removed.当初始同步完成并且节点达到SECONDARY状态时,newlyAdded字段将自动删除。

Note注意
  • Configurations that attempt to add a field named newlyAdded will error even if run with { force: true }.尝试添加名为newlyAdded的字段的配置即使使用{ force: true }运行也会出错。
  • If an existing node has a newlyAdded field, using rs.reconfig() to change the configuration will not remove the newlyAdded field. 如果现有节点具有newlyAdded字段,则使用rs.reconfig()更改配置不会删除newlyAdded域。The newlyAdded field will be appended to the user provided configuration.newlyAdded字段将附加到用户提供的配置中。
  • replSetGetConfig will remove any newlyAdded fields from its output. 将从其输出中删除任何newlyAdded字段。If you would like to see any newlyAdded fields, you can query the local.system.replset collection directly.如果您想查看任何newlyAdded字段,可以直接查询local.system.replset集合。

Examples示例

A replica set named rs0 has the following configuration:名为rs0的副本集具有以下配置:

{
   "_id" : "rs0",
   "version" : 1,
   "protocolVersion" : NumberLong(1),
   "members" : [
      {
         "_id" : 0,
         "host" : "mongodb0.example.net:27017",
         "arbiterOnly" : false,
         "buildIndexes" : true,
         "hidden" : false,
         "priority" : 1,
         "tags" : {
         },
         "secondaryDelaySecs" : NumberLong(0),
         "votes" : 1
      },
      {
         "_id" : 1,
         "host" : "mongodb1.example.net:27017",
         "arbiterOnly" : false,
         "buildIndexes" : true,
         "hidden" : false,
         "priority" : 1,
         "tags" : {
         },
         "secondaryDelaySecs" : NumberLong(0),
         "votes" : 1
      },
      {
         "_id" : 2,
         "host" : "mongodb2.example.net:27017",
         "arbiterOnly" : false,
         "buildIndexes" : true,
         "hidden" : false,
         "priority" : 1,
         "tags" : {
         },
         "secondaryDelaySecs" : NumberLong(0),
         "votes" : 1
      }
   ],
   "settings" : {
      "chainingAllowed" : true,
      "heartbeatIntervalMillis" : 2000,
      "heartbeatTimeoutSecs" : 10,
      "electionTimeoutMillis" : 10000,
      "catchUpTimeoutMillis" : 2000,
      "getLastErrorModes" : {
      },
      "getLastErrorDefaults" : {
         "w" : 1,
         "wtimeout" : 0
      },
      "replicaSetId" : ObjectId("58858acc1f5609ed986b641b")
   }
}

Change Replica Set Member Priority更改副本集成员优先级

The following sequence of operations updates the members[n].priority of the second member. 以下操作序列更新第二个成员的members[n].priorityThe operations are issued through a mongosh session that is connected to the primary.这些操作是通过连接到主会话的mongosh会话发出的。

cfg = rs.conf();
cfg.members[1].priority = 2;
rs.reconfig(cfg);
  1. The first statement uses the rs.conf() method to retrieve a document containing the current configuration for the replica set and sets the document to the local variable cfg.第一条语句使用rs.conf()方法检索包含副本集当前配置的文档,并将该文档设置为本地变量cfg
  2. The second statement sets a members[n].priority value to the second document in the members array. 第二条语句为members数组中的第二个文档设置members[n].priority值。For additional settings, see replica set configuration settings.有关其他设置,请参阅副本集配置设置

    To access the member configuration document in the array, the statement uses the array index and not the replica set member's members[n]._id field.要访问数组中的成员配置文档,该语句使用数组索引而不是副本集成员的members[n]._id字段。

  3. The last statement calls the rs.reconfig() method with the modified cfg to initialize this new configuration. 最后一条语句使用修改后的cfg调用rs.reconfig()方法来初始化这个新配置。Upon successful reconfiguration, the replica set configuration will resemble the following:成功重新配置后,副本集配置将如下所示:
{
   "_id" : "rs0",
   "version" : 2,
   "protocolVersion" : NumberLong(1),
   "members" : [
      {
         "_id" : 0,
         "host" : "mongodb0.example.net:27017",
         "arbiterOnly" : false,
         "buildIndexes" : true,
         "hidden" : false,
         "priority" : 1,
         "tags" : {
         },
         "secondaryDelaySecs" : NumberLong(0),
         "votes" : 1
      },
      {
         "_id" : 1,
         "host" : "mongodb1.example.net:27017",
         "arbiterOnly" : false,
         "buildIndexes" : true,
         "hidden" : false,
         "priority" : 2,
         "tags" : {
         },
         "secondaryDelaySecs" : NumberLong(0),
         "votes" : 1
      },
      {
         "_id" : 2,
         "host" : "mongodb2.example.net:27017",
         "arbiterOnly" : false,
         "buildIndexes" : true,
         "hidden" : false,
         "priority" : 1,
         "tags" : {
         },
         "secondaryDelaySecs" : NumberLong(0),
         "votes" : 1
      }
   ],
   "settings" : {
      "chainingAllowed" : true,
      "heartbeatIntervalMillis" : 2000,
      "heartbeatTimeoutSecs" : 10,
      "electionTimeoutMillis" : 10000,
      "catchUpTimeoutMillis" : 2000,
      "getLastErrorModes" : {
      },
      "getLastErrorDefaults" : {
         "w" : 1,
         "wtimeout" : 0
      },
      "replicaSetId" : ObjectId("58858acc1f5609ed986b641b")
   }
}

Change Replica Set Settings更改副本集设置

You can also modify the cluster replica set settings document. 您还可以修改群集副本集settings文档。The settings document contains configuration options that apply to the whole replica set.settings文档包含适用于整个复制集的配置选项。

The following sequence of operations updates the settings.heartbeatTimeoutSecs of the cluster to 15. 以下操作序列将群集的设置settings.heartbeatTimeoutSecs更新为15The operations are issued through a mongosh session that is connected to the primary.这些操作是通过连接到主会话的mongosh会话发出的。

cfg = rs.conf();
cfg.settings.heartbeatTimeoutSecs = 15;
rs.reconfig(cfg);
←  rs.printSlaveReplicationInfo()rs.reconfigForPSASet() →