Range-based sharding helps split big data into smaller parts based on value ranges. This makes searching and managing data faster and easier.
0
0
Range-based sharding in MongoDB
Introduction
When you have a large collection of data that grows over time.
When you want to quickly find data within certain value ranges, like dates or numbers.
When you want to balance data across servers to avoid overload.
When your data naturally groups into ranges, like user IDs or timestamps.
Syntax
MongoDB
sh.shardCollection("database.collection", { shardKeyField: 1 })
The shard key field is the field used to split data into ranges.
The value 1 means ascending order for the shard key.
Examples
This command shards the 'orders' collection by the 'orderDate' field in ascending order.
MongoDB
sh.shardCollection("shop.orders", { orderDate: 1 })
This shards the 'data' collection in the 'users' database by 'userId'.
MongoDB
sh.shardCollection("users.data", { userId: 1 })
Sample Program
This example enables sharding on the 'shop' database and shards the 'orders' collection by the 'orderDate' field.
MongoDB
use shop sh.enableSharding("shop") sh.shardCollection("shop.orders", { orderDate: 1 })
OutputSuccess
Important Notes
Choose a shard key that evenly distributes data to avoid hotspots.
Range-based sharding works well when queries often filter by the shard key range.
Changing the shard key after sharding is difficult, so pick carefully.
Summary
Range-based sharding splits data by ranges of shard key values.
It helps scale databases by distributing data across servers.
Pick shard keys that match your common query patterns for best performance.