0
0
MongoDBquery~5 mins

Why sharding is needed in MongoDB

Choose your learning style9 modes available
Introduction

Sharding helps split big data into smaller parts so the database can work faster and handle more users at the same time.

When your database grows too large to fit on one server.
When many users access the database at once and slow down performance.
When you want to spread data across multiple servers to avoid overload.
When you need to keep your app running smoothly as data and traffic increase.
Syntax
MongoDB
Sharding is set up by choosing a shard key and enabling sharding on a collection.
A shard key decides how data is split across servers.
Sharding helps with scaling databases horizontally.
Examples
This example enables sharding on a database and shards a collection by the userId field.
MongoDB
sh.enableSharding("myDatabase")
sh.shardCollection("myDatabase.myCollection", { userId: 1 })
Here, orders are sharded by orderDate to distribute data by time.
MongoDB
sh.enableSharding("shopDB")
sh.shardCollection("shopDB.orders", { orderDate: 1 })
Sample Program

This command enables sharding on the testDB database and shards the customers collection by customerId.

MongoDB
sh.enableSharding("testDB")
sh.shardCollection("testDB.customers", { customerId: 1 })
OutputSuccess
Important Notes

Choosing the right shard key is important for good performance.

Sharding helps databases grow without slowing down.

Summary

Sharding splits big data to keep databases fast.

It spreads data across servers to handle more users.

Use sharding when your data or traffic grows too large for one server.