- Reference >
- Database Commands >
- Sharding Commands >
- shardCollection
shardCollection¶
On this page
Definition¶
-
shardCollection
¶ Shards a collection to distribute its documents across shards. You must run
enableSharding
on a database before running theshardCollection
command. TheshardCollection
command must be run against theadmin
database.To run
shardCollection
, use thedb.runCommand( { <command> } )
method.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 shard key determines how MongoDB distributes the documents among the shards.
Unless the collection is empty, the index must exist prior to the
shardCollection
command. If the collection is empty, MongoDB creates the index prior to sharding the collection if the index that can support the shard key does not already exist.See also Shard Key Indexes
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¶
You can only shard a collection once.
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 and restrictions.
Hashed Shard Keys¶
Hashed shard keys use a hashed index of a single field as the shard key.
Use the form {field: "hashed"}
to specify a hashed shard key.
Hashed shard keys may not be compound indexes.
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.
See also
Uniqueness¶
If specifying unique: true
:
- If the collection is empty,
shardCollection
creates the unique index on the shard key if such an index does not already exists. - If the collection is not empty, you must create the index first
before using
shardCollection
.
Although you can have a unique compound index where the shard
key is a prefix, if using unique
parameter, the collection must have a unique index that is on the shard
key.