Working with Sharding
1. Understanding Sharded Cluster Architecture
Apps
│
┌──▼──┐
│mongos│ (router)
└──┬──┘
┌────────┼────────┐
Shard1 Shard2 Shard3 ── data shards (each a replica set)
│
Config Servers (CSRS)
| Component | Role |
| mongos | Query router |
| Config server | Cluster metadata (replica set) |
| Shard | Holds subset of data (replica set) |
2. Setting Up Config Servers
| Aspect | Detail |
| Mode | --configsvr replica set (CSRS) |
| Required | 3-member replica set in production |
3. Setting Up mongos Query Routers
| Aspect | Detail |
| Start | mongos --configdb csrs/cfg1,cfg2,cfg3 |
| Stateless | Run multiple for HA + load distribution |
4. Enabling Sharding
sh.enableSharding("appdb");
| Method | Detail |
| sh.enableSharding(db) | Allow sharding for database |
| sh.status() | Inspect cluster state |
5. Choosing Shard Key
| Quality | Detail |
| High cardinality | Many unique values |
| Low frequency | Even value distribution |
| Non-monotonic | Avoid hotspots (or use hashed) |
| Query alignment | Used in common queries → targeted routing |
6. Sharding Collection
sh.shardCollection("appdb.orders", { customerId: "hashed" });
| Step | Detail |
| Index | Must exist on shard key |
| Reshardable | 5.0+ via reshardCollection |
7. Using Hashed Shard Key
| Pros | Cons |
| Even distribution | Range queries scatter |
| No hotspot | No locality |
8. Using Ranged Shard Key
| Pros | Cons |
| Range queries efficient | Monotonic key → hotspots |
9. Using Compound Shard Key
| Pattern | Detail |
| {tenantId:1, _id:1} | Tenant locality + uniqueness |
| {country:1, userId:"hashed"} 4.4+ | Compound hashed shard key |
10. Adding Shards
| Method | Form |
| sh.addShard("rs1/m1:27018,m2:27018") | Add a replica-set shard |
11. Removing Shards
| Method | Detail |
| removeShard | Run repeatedly until completed |
| Drains | Chunks moved off automatically |
12. Understanding Chunk Management
| Aspect | Detail |
| Chunk size | Default 128MB (6.0+); 64MB earlier |
| Balancer | Moves chunks to keep shards balanced |
| Splits | Auto when chunk too large |