- 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
enableSharding
on a database before running theshardCollection
command.shardCollection
has the following form: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
, theunique
option ensures that the underlying index enforces a unique constraint. Hashed shard keys do not support unique constraints.numInitialChunks
integer Specifies the number of chunks to create initially when sharding an empty collection with a hashed shard key. MongoDB will then create and balance chunks across the cluster. The numInitialChunks
must be less than8192
per shard. If the collection is not empty,numInitialChunks
has no effect.
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.
Note
If chunk migrations are in progress while creating a hashed shard key collection, the initial chunk distribution may be uneven until the balancer automatically balances the collection.
Example¶
The following operation enables sharding for the people
collection
in the records
database and uses the zipcode
field as the
shard key: