Sharding
Sharding is MongoDB's horizontal scaling mechanism — distributing data across multiple servers (shards). When a single server can no longer handle the data volume or write throughput, sharding is the solution.
When to Shard
Data size exceeds what fits comfortably on one server
Write throughput exceeds one server's capacity (millions of writes/sec)
Working set (frequently accessed data) exceeds available RAM
Geographically distributed data with low-latency requirements
Sharded Cluster Components
Component | Role | Notes |
|---|---|---|
Shard | Stores a subset of the data | Each shard is a replica set |
mongos | Query router — routes client requests to correct shard(s) | Stateless, deploy multiple |
Config servers | Store cluster metadata and chunk map | 3-node replica set |
The Shard Key
The shard key is the field (or compound fields) MongoDB uses to distribute documents across shards. Choosing the right shard key is the most critical decision in sharding.
High cardinality — many unique values enable even distribution
Low frequency skew — avoid keys where a few values dominate (a celebrity user's data shouldn't fill one shard)
Non-monotonic — avoid auto-increment IDs and timestamps as shard keys; all new writes go to the last shard, creating a hotspot
Range vs Hashed Sharding
Type | How It Works | Best For | Weakness |
|---|---|---|---|
Range | Adjacent key values go to same shard | Range queries on shard key | Monotonic keys create hotspots |
Hashed | Hash of key distributes randomly | Write throughput, even distribution | Range queries scatter to all shards |
Enable sharding and shard a collection
// Enable sharding for a database
sh.enableSharding('mydb')
// Range sharding — good for range queries on customerId
sh.shardCollection('mydb.orders', { customerId: 1 })
// Hashed sharding — good for even write distribution
sh.shardCollection('mydb.events', { userId: 'hashed' })
// Compound shard key
sh.shardCollection('mydb.logs', { tenantId: 1, createdAt: 1 })Zone Sharding
Zone sharding maps shard key ranges to specific shards — useful for keeping EU user data on EU servers for GDPR compliance, or hot data on fast SSDs.
Zone sharding for geo-distribution
// Tag a shard as EU
sh.addShardTag('shard01', 'EU')
// Route EU user documents to EU shard
sh.addTagRange(
'mydb.users',
{ region: 'EU', userId: MinKey },
{ region: 'EU', userId: MaxKey },
'EU'
)Monitoring a Sharded Cluster
Sharding status
sh.status() // full cluster status
db.orders.getShardDistribution() // docs per shard
db.adminCommand({ listShards: 1 }) // shard list
db.adminCommand({ balancerStatus: 1 }) // balancer running?Chunks and Balancing
MongoDB divides the shard key space into chunks (default 128 MB). The balancer migrates chunks between shards automatically in the background to maintain even distribution. Chunk splits and migrations are transparent to the application.