How does sharding work in MongoDB?
Sharding horizontally partitions a collection across mongos routers and shards. You choose a shard key, and MongoDB splits the key space into chunks distributed and balanced across shards.
Two strategies:
- Ranged sharding: contiguous key ranges per shard, good for range queries but can create hotspots on monotonic keys.
- Hashed sharding: hashes the key for even distribution, good for write scaling but poor for range queries.
The shard key must be present in every document and is immutable in older versions. A poor key causes jumbo chunks or an unbalanced cluster; a monotonically increasing timestamp sends all writes to one shard. Include a high-cardinality, frequently queried field, or use a compound key combining a coarse partition with a fine field. Queries including the shard key are targeted; others become scatter-gather and hit every shard.