Introduction
Choosing the right shard key helps your database split data evenly and find data quickly.
Choosing the right shard key helps your database split data evenly and find data quickly.
sh.shardCollection("database.collection", { shardKeyField: 1 })
sh.shardCollection("shop.orders", { orderId: 1 })
sh.shardCollection("users.data", { userId: 1, region: 1 })
This example enables sharding on the 'shop' database and sets 'orderId' as the shard key for the 'orders' collection.
use shop sh.enableSharding("shop") sh.shardCollection("shop.orders", { orderId: 1 })
A bad shard key can cause uneven data distribution, making some servers overloaded.
Choose a shard key with many different values to spread data well.
Shard keys cannot be changed easily after setting, so choose carefully.
Shard keys decide how data is split across servers.
Good shard keys keep data balanced and queries fast.
Pick shard keys with many unique values and that match your query patterns.
{ userId: 1 } in MongoDB?{ orderId: 1 }, which query will benefit most from the shard key?orderId uses the shard key, so it benefits most.{ country: 1 } but notice one shard stores 90% of data. What is the likely problem?Pass the test and this pattern moves unknown