Navigation

Manage Shard Zones

In sharded clusters, you can create zones that represent a group of shards and associate one or more ranges of shard key values to that zone. MongoDB routes reads and writes that fall into a zone range only to those shards inside of the zone.

Add Shards to a Zone

Associate a Zone with a particular shard using the sh.addShardTag() method when connected to a mongos instance. A single shard may have multiple zones, and multiple shards may also have the same zone.

Example

The following example adds the zone NYC to two shards, and the zones SFO and NRT to a third shard:

sh.addShardTag("shard0000", "NYC")
sh.addShardTag("shard0001", "NYC")
sh.addShardTag("shard0002", "SFO")
sh.addShardTag("shard0002", "NRT")

You may remove zone from a particular shard using the sh.removeShardTag() method when connected to a mongos instance, as in the following example, which removes the NRT zone from a shard:

sh.removeShardTag("shard0002", "NRT")

Create a Zone Range

To define the zone’s range of shard keys, use the sh.addTagRange() method when connected to a mongos instance. Any given shard key range may only have one assigned zone. You cannot overlap defined ranges.

Example

Given a collection named users in the records database, sharded by the zipcode field. The following operations assign:

  • two ranges of zip codes in Manhattan and Brooklyn the NYC zone
  • one range of zip codes in San Francisco the SFO zone
sh.addTagRange("records.users", { zipcode: "10001" }, { zipcode: "10281" }, "NYC")
sh.addTagRange("records.users", { zipcode: "11201" }, { zipcode: "11240" }, "NYC")
sh.addTagRange("records.users", { zipcode: "94102" }, { zipcode: "94135" }, "SFO")

Note

Zone ranges are always inclusive of the lower boundary and exclusive of the upper boundary.

Remove a Zone Range

New in version 3.4: Use the shell helper method sh.removeRangeFromZone() to remove a range from a zone.

Example

The following example removes the NYC zone assignment for the range of zip codes within Manhattan:

sh.removeRangeFromZone("records.user", {zipcode: "10001"}, {zipcode: "10281"})

View Existing Zones

Use sh.status() to list the zones associated to each shard in the cluster. You can also view a shards zones by querying the shards collection in the config database.

The following example uses the find() method to return all shards with the NYC zone.

use config
db.shards.find({ tags: "NYC" })

You can find zone ranges for all namespaces in the tags collection of the config database. The output of sh.status() also displays all zone ranges.

The following example uses the find() method to return any range associated to the NYC zone.

use config
db.tags.find({ tags: "NYC" })