0
0
MongoDBquery~5 mins

Hash-based sharding in MongoDB

Choose your learning style9 modes available
Introduction

Hash-based sharding helps split data evenly across many servers. It makes sure no single server gets too much work.

When you have a large collection that needs to be split across multiple servers.
When you want to balance the load evenly without worrying about data order.
When your queries mostly use the shard key for fast lookups.
When you want to avoid hotspots caused by sequential data inserts.
When you want to scale your database horizontally by adding more servers.
Syntax
MongoDB
sh.shardCollection("database.collection", { "shardKeyField": "hashed" })
The shard key field must be indexed and present in all documents.
Hashing the shard key spreads data randomly but evenly across shards.
Examples
This command shards the orders collection in the shop database using a hashed orderId field.
MongoDB
sh.shardCollection("shop.orders", { "orderId": "hashed" })
This shards the profiles collection by hashing the userId field to distribute user data evenly.
MongoDB
sh.shardCollection("users.profiles", { "userId": "hashed" })
Sample Program

This example enables sharding on the shop database and shards the orders collection using a hashed orderId field.

MongoDB
use admin
sh.enableSharding("shop")
sh.shardCollection("shop.orders", { "orderId": "hashed" })
OutputSuccess
Important Notes

Hash-based sharding works best when your shard key has high cardinality (many unique values).

It is not good for range queries because hashed keys do not preserve order.

Once you shard a collection, changing the shard key is difficult.

Summary

Hash-based sharding splits data evenly by hashing the shard key.

It helps balance load and avoid hotspots.

Use it when you want even data distribution without caring about order.