OPTIONS

shardCollection

Definition

shardCollection

Enables a collection for sharding and allows MongoDB to begin distributing data among shards. You must run enableSharding on a database before running the shardCollection command. shardCollection has the following form:

{ shardCollection: "<database>.<collection>", key: <shardkey> }

shardCollection has the following fields:

Field Type Description
shardCollection string The namespace of the collection to shard in the form <database>.<collection>.
key document The index specification document to use as the shard key. The index must exist prior to the shardCollection command, unless the collection is empty. If the collection is empty, in which case MongoDB creates the index prior to sharding the collection. New in version 2.4: The key may be in the form { field : "hashed" }, which will use the specified field as a hashed shard key.
unique Boolean When true, the unique option ensures that the underlying index enforces a unique constraint. Hashed shard keys do not support unique constraints.
numInitialChunks integer To support hashed sharding added in MongoDB 2.4, numInitialChunks specifies the number of chunks to create when sharding an collection with a hashed shard key. MongoDB will then create and balance chunks across the cluster. The numInitialChunks must be less than 8192 per shard.

Considerations

Use

Do not run more than one shardCollection command on the same collection at the same time.

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.

Shard Keys

Choosing the best shard key to effectively distribute load among your shards requires some planning. Review Shard Keys regarding choosing a shard key.

Hashed Shard Keys

New in version 2.4.

Hashed shard keys use a hashed index of a single field as the shard key.

Example

The following operation enables sharding for the people collection in the records database and uses the zipcode field as the shard key:

db.runCommand( { shardCollection: "records.people", key: { zipcode: 1 } } )

Additional Information

Sharding, Sharding Concepts, and Deploy a Sharded Cluster.