0
0
MongoDBquery~5 mins

Shard key selection importance in MongoDB

Choose your learning style9 modes available
Introduction

Choosing the right shard key helps your database split data evenly and find data quickly.

When you want to store lots of data across many servers.
When your app needs fast access to specific pieces of data.
When you want to avoid some servers getting too busy while others are idle.
When you plan to grow your database size over time.
When you want to keep your database reliable and fast.
Syntax
MongoDB
sh.shardCollection("database.collection", { shardKeyField: 1 })
The shard key is a field or fields used to split data across servers.
Use 1 for ascending order or -1 for descending order in the shard key.
Examples
This sets 'orderId' as the shard key to split the 'orders' collection.
MongoDB
sh.shardCollection("shop.orders", { orderId: 1 })
This uses a compound shard key with 'userId' and 'region' to distribute data.
MongoDB
sh.shardCollection("users.data", { userId: 1, region: 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 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.

Summary

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.