0% completed
Sharding is a method used to distribute data across multiple servers to ensure scalability and performance. It allows MongoDB to handle large datasets and high throughput operations by dividing the data into smaller, more manageable pieces called shards.
Shard:
Shard Key:
Config Server:
Query Router (mongos):
Data Distribution:
Query Routing:
Rebalancing:
Scalability:
High Throughput:
Fault Tolerance:
Start Config Servers:
mongod --configsvr --replSet configReplSet --port 27019 --dbpath /data/config1 mongod --configsvr --replSet configReplSet --port 27020 --dbpath /data/config2 mongod --configsvr --replSet configReplSet --port 27021 --dbpath /data/config3
Initiate Config Server Replica Set:
mongo --port 27019 rs.initiate() rs.add("localhost:27020") rs.add("localhost:27021")
Start Shard Servers:
mongod --shardsvr --replSet shardReplSet1 --port 27022 --dbpath /data/shard1 mongod --shardsvr --replSet shardReplSet1 --port 27023 --dbpath /data/shard2
Initiate Shard Replica Set:
mongo --port 27022 rs.initiate() rs.add("localhost:27023")
Start Mongos Instances:
mongos --configdb configReplSet/localhost:27019,localhost:27020,localhost:27021 --port 27017
Add Shards to the Cluster:
mongo --port 27017 sh.addShard("shardReplSet1/localhost:27022,localhost:27023")
Enable Sharding for a Database:
sh.enableSharding("myDatabase")
Shard a Collection:
sh.shardCollection("myDatabase.myCollection", {shardKey: 1})
Start Config Servers:
mongod --configsvr --replSet configReplSet --port 27019 --dbpath /data/config1 mongod --configsvr --replSet configReplSet --port 27020 --dbpath /data/config2 mongod --configsvr --replSet configReplSet --port 27021 --dbpath /data/config3
Initiate Config Server Replica Set:
mongo --port 27019 rs.initiate() rs.add("localhost:27020") rs.add("localhost:27021")
Start Shard Servers:
mongod --shardsvr --replSet shardReplSet1 --port 27022 --dbpath /data/shard1 mongod --shardsvr --replSet shardReplSet1 --port 27023 --dbpath /data/shard2
Initiate Shard Replica Set:
mongo --port 27022 rs.initiate() rs.add("localhost:27023")
Start Mongos Instances:
mongos --configdb configReplSet/localhost:27019,localhost:27020,localhost:27021 --port 27017
Add Shards to the Cluster:
mongo --port 27017 sh.addShard("shardReplSet1/localhost:27022,localhost:27023")
Enable Sharding for a Database:
sh.enableSharding("myDatabase")
Shard a Collection:
sh.shardCollection("myDatabase.myCollection", {shardKey: 1})
Sharding in MongoDB is essential for handling large datasets and high traffic loads. By distributing data across multiple shards, you can achieve horizontal scalability, high throughput, and fault tolerance. Setting up a sharded cluster involves configuring config servers, shard servers, and mongos instances, along with selecting appropriate shard keys to ensure efficient data distribution.
Next, we can cover Change Streams, but let me know if you have any questions about sharding first!
.....
.....
.....