Lab 16: MongoDB Sharding
Overview
Step 1: Architecture Overview and Setup
# MongoDB sharding requires:
# 1. Config servers (3-node replica set) - store cluster metadata
# 2. Shard servers (1+ replica sets) - store actual data
# 3. mongos router - application connection point
docker network create mongo-shard-net
# Start config server (single node for lab simplicity)
docker run -d \
--name mongo-config \
--network mongo-shard-net \
--hostname mongo-config \
mongo:7 \
--configsvr \
--replSet configRs \
--bind_ip_all
# Start shard 1
docker run -d \
--name mongo-shard1 \
--network mongo-shard-net \
--hostname mongo-shard1 \
mongo:7 \
--shardsvr \
--replSet shard1Rs \
--bind_ip_all
# Start shard 2
docker run -d \
--name mongo-shard2 \
--network mongo-shard-net \
--hostname mongo-shard2 \
mongo:7 \
--shardsvr \
--replSet shard2Rs \
--bind_ip_all
# Wait for all to start
sleep 10
for svc in mongo-config mongo-shard1 mongo-shard2; do
for i in $(seq 1 30); do
docker exec $svc mongosh --quiet --eval "db.runCommand({ping:1})" 2>/dev/null | grep -q "ok.*1" && break || sleep 2
done
echo "$svc ready"
doneStep 2: Initialize Config Server and Shards as Replica Sets
Step 3: Add Shards to the Cluster
Step 4: Enable Sharding on Database and Collection
Step 5: Insert Data and Observe Shard Distribution
Step 6: sh.status() — Detailed Cluster Status
Step 7: Range vs Hashed Shard Key Analysis
Step 8: Capstone — Add a Third Shard and Watch Balancer
Summary
Component
Role
Command
Key Takeaways
Last updated
