- Sharding >
- Sharded Cluster Tutorials >
- Sharded Cluster Deployment Tutorials >
- Shard a Collection Using a Hashed Shard Key
Shard a Collection Using a Hashed Shard Key¶
On this page
New in version 2.4.
Hashed shard keys use a hashed index of a field as the shard key to partition data across your sharded cluster.
For suggestions on choosing the right field as your hashed shard key, see Hashed Shard Keys. For limitations on hashed indexes, see Create a Hashed Index.
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.
Shard the Collection¶
To shard a collection using a hashed shard key, use an operation in
the mongo
that resembles the following:
This operation shards the active
collection in the records
database, using a hash of the a
field as the shard key.
Specify the Initial Number of Chunks¶
If you shard an empty collection using a hashed shard key, MongoDB
automatically creates and migrates empty chunks so that each shard
has two chunks. To control how many chunks MongoDB creates when
sharding the collection, use shardCollection
with the
numInitialChunks
parameter.
Important
MongoDB 2.4 adds support for hashed shard keys. After
sharding a collection with a hashed shard key, you must use the
MongoDB 2.4 or higher mongos
and mongod
instances in your sharded cluster.
Warning
MongoDB hashed
indexes truncate floating point numbers to 64-bit integers
before hashing. For example, a hashed
index would store the same
value for a field that held a value of 2.3
, 2.2
, and 2.9
.
To prevent collisions, do not use a hashed
index for floating
point numbers that cannot be reliably converted to 64-bit
integers (and then back to floating point). MongoDB hashed
indexes do
not support floating point values larger than 253.