Working with Sharding

1. Understanding Sharded Cluster Architecture

            Apps
              │
           ┌──▼──┐
           │mongos│ (router)
           └──┬──┘
     ┌────────┼────────┐
   Shard1  Shard2  Shard3   ── data shards (each a replica set)
              │
        Config Servers (CSRS)
      
ComponentRole
mongosQuery router
Config serverCluster metadata (replica set)
ShardHolds subset of data (replica set)

2. Setting Up Config Servers

AspectDetail
Mode--configsvr replica set (CSRS)
Required3-member replica set in production

3. Setting Up mongos Query Routers

AspectDetail
Startmongos --configdb csrs/cfg1,cfg2,cfg3
StatelessRun multiple for HA + load distribution

4. Enabling Sharding

sh.enableSharding("appdb");
MethodDetail
sh.enableSharding(db)Allow sharding for database
sh.status()Inspect cluster state

5. Choosing Shard Key

QualityDetail
High cardinalityMany unique values
Low frequencyEven value distribution
Non-monotonicAvoid hotspots (or use hashed)
Query alignmentUsed in common queries → targeted routing

6. Sharding Collection

sh.shardCollection("appdb.orders", { customerId: "hashed" });
StepDetail
IndexMust exist on shard key
Reshardable5.0+ via reshardCollection

7. Using Hashed Shard Key

ProsCons
Even distributionRange queries scatter
No hotspotNo locality

8. Using Ranged Shard Key

ProsCons
Range queries efficientMonotonic key → hotspots

9. Using Compound Shard Key

PatternDetail
{tenantId:1, _id:1}Tenant locality + uniqueness
{country:1, userId:"hashed"} 4.4+Compound hashed shard key

10. Adding Shards

MethodForm
sh.addShard("rs1/m1:27018,m2:27018")Add a replica-set shard

11. Removing Shards

MethodDetail
removeShardRun repeatedly until completed
DrainsChunks moved off automatically

12. Understanding Chunk Management

AspectDetail
Chunk sizeDefault 128MB (6.0+); 64MB earlier
BalancerMoves chunks to keep shards balanced
SplitsAuto when chunk too large