movePrimary

  • movePrimary
  • In a sharded cluster, movePrimary reassigns theprimary shard which holds all un-sharded collections inthe database. movePrimary first changes the primary shard inthe cluster metadata, and then migrates all un-sharded collections to thespecified shard. Use the command with the following form:
  1. db.adminCommand( { movePrimary: <databaseName>, to: <newPrimaryShard> } )

For example, the following command moves the primary shard from test toshard0001:

  1. db.adminCommand( { movePrimary : "test", to : "shard0001" } )

When the command returns, the database’s primary shard locationhas switched to the specified shard. To fully decommission ashard, use the removeShard command.

Note

The destination shard must rebuild its indexesin the foreground when it becomes the primary shard.The collection locks while the indexes are building,preventing reads and writes until the indexes are finished.See Index Builds on Populated Collections for details.

movePrimary is an administrative command that is only availablefor mongos instances.

Considerations

Warning

  • Starting in MongoDB 4.2:
  • If you use the movePrimary command to move _unsharded_collections, you must either:

    • Restart all mongos instances and allmongod shard members (including the secondarymembers);
    • Use the flushRouterConfig command on allmongos instances and all mongodshard members (including the secondary members) before readingor writing any data to any unsharded collections that weremoved.Otherwise, the you may miss data on reads, and may not write data tothe correct shard. To recover, you must manually intervene.
  • In MongoDB 4.0 and earlier:

  • If you use the movePrimary command to move un-shardedcollections, you must either restart all mongos instances,or use the flushRouterConfig command on allmongos instances before reading or writing any data to anyunsharded collections that were moved. This action ensures that themongos is aware of the new shard for these collections.

If you do not update the mongos instances’ metadata cacheafter using movePrimary, the mongos may miss dataon reads, and may not write data to the correct shard. To recover, you mustmanually intervene.

Otherwise, the you may miss data on reads, and may not write data tothe correct shard. To recover, you must manually intervene.

Avoid accessing an un-sharded collection during migration.movePrimary does not prevent reading and writing during itsoperation, and such actions yield undefined behavior.

movePrimary may take significant time to complete, andyou should plan for this unavailability.

mongos uses "majority" formovePrimary.

movePrimary will fail if the destination shard contains aconflicting collection name. This may occur if documents are written to anun-sharded collection while the collection is moved away, and later the originalprimary shard is restored.

Additional Information

See Remove Shards from an Existing Sharded Cluster for a completeprocedure.