0
0
MongoDBquery~5 mins

Chunks and balancer concept in MongoDB

Choose your learning style9 modes available
Introduction
Chunks help split large data into smaller parts for easier management. The balancer moves these parts to keep data spread evenly across servers.
When your database grows too big for one server to handle.
When you want to make queries faster by spreading data.
When you want to avoid one server getting too busy while others are idle.
When you add new servers and want data to move to them automatically.
Syntax
MongoDB
sh.enableSharding("databaseName")
sh.shardCollection("databaseName.collectionName", { orderId: 1 })
sh.status()
sh.startBalancer()
sh.stopBalancer()
Use sh.enableSharding() to turn on sharding for a database.
Use sh.shardCollection() to split a collection into chunks based on a shard key.
Examples
Enable sharding on the database named 'shopDB'.
MongoDB
sh.enableSharding("shopDB")
Shard the 'orders' collection in 'shopDB' using 'orderId' as the shard key.
MongoDB
sh.shardCollection("shopDB.orders", { orderId: 1 })
Check the current sharding status, including chunks and balancer activity.
MongoDB
sh.status()
Start the balancer to redistribute chunks evenly across shards.
MongoDB
sh.startBalancer()
Sample Program
This example enables sharding on 'libraryDB', shards the 'books' collection by 'isbn', shows the sharding status, and starts the balancer to distribute chunks evenly.
MongoDB
sh.enableSharding("libraryDB")
sh.shardCollection("libraryDB.books", { isbn: 1 })
sh.status()
sh.startBalancer()
OutputSuccess
Important Notes
Chunks are ranges of data based on the shard key values.
The balancer runs in the background and moves chunks to keep data balanced.
You can monitor chunk distribution with sh.status().
Summary
Chunks split data into smaller parts for easier handling.
The balancer moves chunks to keep data evenly spread across servers.
Sharding improves performance and scalability by distributing data.