- Reference >
- Database Commands >
- Sharding Commands >
- shardCollection
shardCollection¶
On this page
Definition¶
-
shardCollection¶ Enables a collection for sharding and allows MongoDB to begin distributing data among shards. You must run
enableShardingon a database before running theshardCollectioncommand.shardCollectionhas the following form:shardCollectionhas the following fields:Field Type Description shardCollectionstring The namespace of the collection to shard in the form <database>.<collection>.keydocument The index specification document to use as the shard key. The index must exist prior to the shardCollectioncommand, 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.uniqueBoolean When true, theuniqueoption ensures that the underlying index enforces a unique constraint. Hashed shard keys do not support unique constraints.numInitialChunksinteger To support hashed sharding added in MongoDB 2.4, numInitialChunksspecifies 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. ThenumInitialChunksmust be less than8192per shard.
Considerations¶
Use¶
Do not run more than one shardCollection command on
the same collection at the same time.
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.
Warning
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¶
The following operation enables sharding for the people collection
in the records database and uses the zipcode field as the
shard key: