OPTIONS

sh.shardCollection()

Definition

sh.shardCollection(namespace, key, unique)

Shards a collection using the key as a the shard key. sh.shardCollection() takes the following arguments:

Parameter Type Description
namespace string The namespace of the collection to shard.
key document A document that specifies the shard key to use to partition and distribute objects among the shards. A shard key may be one field or multiple fields. A shard key with multiple fields is called a “compound shard key.”
unique Boolean When true, ensures that the underlying index enforces a unique constraint. Hashed shard keys do not support unique constraints.

New in version 2.4: Use the form {field: "hashed"} to create a hashed shard key. Hashed shard keys may not be compound indexes.

Considerations

MongoDB provides no method to deactivate sharding for a collection after calling shardCollection. Additionally, after shardCollection, you cannot change shard keys or modify the value of any field used in your shard key index.

Example

Given the people collection in the records database, the following command shards the collection by the zipcode field:

sh.shardCollection("records.people", { zipcode: 1} )

Additional Information

shardCollection for additional options, Sharding and Sharding Introduction for an overview of sharding, Deploy a Sharded Cluster for a tutorial, and Shard Keys for choosing a shard key.