Database Manual / Sharding / Balancer

Migrate Ranges in a Sharded Cluster

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

To manually migrate ranges, use the moveChunk or moveRange command.

For more information on how the automatic balancer moves ranges between shards, see Balancer Internals and Range Migration.

Example

Migrate a single range

The following example assumes that the field username is the shard key for a collection named users in the myapp database, and that the value smith exists within the range to migrate. Migrate the range using the following command in mongosh.

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

This command moves the range that includes the shard key value "smith" to the shard named mongodb-shard3.example.net. The command will block until the migration is complete.

Tip

To return a list of shards, use the listShards command.

Example

Evenly migrate ranges

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

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

See Create Ranges in a Sharded Cluster for an introduction to pre-splitting.

See moveChunk and moveRange for details.

Change Streams and Orphan Documents

Starting in MongoDB 5.3, during range migration, change stream events are not generated for updates to orphaned documents.