Hashed sharding assigns documents to chunk ranges using hash values derived from shard-key values. It spreads writes more evenly when keys increase predictably, such as ObjectId values or timestamps, instead of concentrating inserts on one shard. section 7.2.7 section 9.3.4
Use hashed sharding with these operational trade-offs in mind:
- Prefer it for monotonically changing shard keys that would otherwise direct new writes to the MaxKey chunk. section 7.2.7 section 9.3.4
- Avoid it when range-based queries are important, because hashed values do not preserve the original ordering of shard-key values. section 9.3.4
- Check field compatibility: floating-point conversion can create collisions, and hashed indexes cannot support array fields or unique constraints directly. section 7.2.7
- Let MongoDB compute hashes during query resolution; applications do not need to calculate them. section 7.2.7
db.<collection>.createIndex(
{
<field>: "hashed"
}
)
Create a single-field hashed index by assigning the shard-key field the value "hashed". section 7.2.7
