0
0
MongoDBquery~5 mins

Choosing a good shard key in MongoDB

Choose your learning style9 modes available
Introduction

Choosing a good shard key helps spread data evenly across servers. This makes your database faster and more reliable.

When your database grows too big for one server.
When you want to make queries faster by splitting data.
When you want to add more servers to handle more users.
When you want to avoid one server getting too busy.
When you want to keep data balanced and easy to find.
Syntax
MongoDB
sh.shardCollection("database.collection", { shardKeyField: 1 })
The shard key is a field or fields used to split data.
Use 1 for ascending or -1 for descending order in the shard key.
Examples
This uses the orderId field as the shard key to split orders.
MongoDB
sh.shardCollection("shop.orders", { orderId: 1 })
This uses userId to distribute user profiles across shards.
MongoDB
sh.shardCollection("users.profiles", { userId: 1 })
This shards data by time, useful for time-based queries.
MongoDB
sh.shardCollection("logs.events", { timestamp: 1 })
Sample Program

This example enables sharding on the 'shop' database and sets 'orderId' as the shard key for the 'orders' collection.

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

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.

Summary

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.