On this page
Hashed Indexes
On this page
Hashed indexes maintain entries with hashes of the values of the indexed field.
Hashed indexes support sharding using hashed shard keys. Hashed based sharding uses a hashed index of a field as the shard key to partition data across your sharded cluster.
Using a hashed shard key to shard a collection results in a more random distribution of data. See Hashed Sharding for more details.
Hashing Function
Hashed indexes use a hashing function to compute the hash of the value of the index field. The hashing function collapses embedded documents and computes the hash for the entire value but does not support multi-key (i.e. arrays) indexes.
Tip
MongoDB automatically computes the hashes when resolving queries using hashed indexes. Applications do not need to compute hashes.
Create a Hashed Index
To create a hashed index, specify hashed
as the value of the index key, as in the following example:
db.collection.createIndex( { _id: "hashed" } )
Considerations
MongoDB supports hashed
indexes of any single field. The hashing function collapses embedded documents and computes the hash for the entire value, but does not support multi-key (i.e. arrays) indexes.
You may not create compound indexes that have hashed
index fields or specify a unique constraint on a hashed
index; however, you can create both a hashed
index and an ascending/descending (i.e. non-hashed) index on the same field: MongoDB will use the scalar index for range queries.
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.