Introduction
Choosing a good shard key helps spread data evenly across servers. This makes your database faster and more reliable.
Choosing a good shard key helps spread data evenly across servers. This makes your database faster and more reliable.
sh.shardCollection("database.collection", { shardKeyField: 1 })
sh.shardCollection("shop.orders", { orderId: 1 })
sh.shardCollection("users.profiles", { userId: 1 })
sh.shardCollection("logs.events", { timestamp: 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 good shard key has many different values to spread data well.
Avoid shard keys that have the same value for many documents, or data will be uneven.
Think about your most common queries when choosing the shard key.
Shard keys split data to improve speed and balance.
Choose a shard key with many unique values.
Pick a shard key that matches how you search your data.
{ userId: 1 } in MongoDB?sh.shardCollection(namespace, shardKey), where namespace is 'database.collection'.{ country: 1 }, which query will benefit most from the shard key?country, the shard key, so it benefits most.{ userId: 1 } but notice all data is stored on one shard. What is the likely cause?userId causes data to be stored on one shard, matching the problem.orderId, customerId, and orderDate. You want to shard to optimize queries filtering by customerId and range queries on orderDate. Which shard key is best?customerId and also use range on orderDate.{ customerId: 1, orderDate: 1 } supports both equality and range queries efficiently.Pass the test and this pattern moves unknown