Migrate Chunks in a Sharded Cluster

In most circumstances, you should let the automatic balancermigrate chunks between shards. However,you may want to migrate chunks manually in a few cases:

  • When pre-splitting an empty collection, migrate chunksmanually to distribute them evenly across the shards. Usepre-splitting in limited situations to support bulk data ingestion.
  • If the balancer in an active cluster cannot distribute chunks withinthe balancing window, thenyou will have to migrate chunks manually.

To manually migrate chunks, use the moveChunk command.For more information on how the automatic balancer moves chunksbetween shards, see Cluster Balancer andChunk Migration.

Example

Migrate a single chunk

The following example assumes that the field username is theshard key for a collection named users in the myappdatabase, and that the value smith exists within the chunkto migrate. Migrate the chunk using the following command in themongo shell.

  1. db.adminCommand( { moveChunk : "myapp.users",
  2. find : {username : "smith"},
  3. to : "mongodb-shard3.example.net" } )

This command moves the chunk that includes the shard key value “smith” to theshard named mongodb-shard3.example.net. The command willblock until the migration is complete.

Tip

To return a list of shards, use the listShardscommand.

Example

Evenly migrate chunks

To evenly migrate chunks for the myapp.users collection,put each prefix chunk on the next shard from the other and runthe following commands in the mongo shell:

  1. var shServer = [ "sh0.example.net", "sh1.example.net", "sh2.example.net", "sh3.example.net", "sh4.example.net" ];
  2. for ( var x=97; x<97+26; x++ ){
  3. for( var y=97; y<97+26; y+=6 ) {
  4. var prefix = String.fromCharCode(x) + String.fromCharCode(y);
  5. db.adminCommand({moveChunk : "myapp.users", find : {email : prefix}, to : shServer[(y-97)/6]})
  6. }
  7. }

See Create Chunks in a Sharded Cluster for an introductionto pre-splitting.

The moveChunk command has the: _secondaryThrottleparameter and the writeConcern parameter that determines when thebalancer proceeds with the next document in the migrating chunk. SeemoveChunk command for details.

Warning

The moveChunk command may produce the following errormessage:

  1. The collection's metadata lock is already taken.

This occurs when clients have too many open cursors that access the migrating chunk. You may eitherwait until the cursors complete their operations or close thecursors manually.