MongoDB Sharding Explained: Shard Keys and Chunks
On this page
When to shard MongoDB
A replica set gives you copies, not capacity: every write still lands on one primary, and every member holds the full dataset. When the data outgrows a server's disks or RAM, or writes outgrow one primary, MongoDB shards: it splits a collection's data across several replica sets, each holding part of it.
Before sharding, make sure you need it. Better indexes, more RAM, a bigger instance and archiving old data carry most applications a long way, and sharding adds permanent complexity.
Shards, mongos and config servers
- Shards: each is a replica set holding a subset of the data.
- mongos: query routers. Applications connect to mongos exactly as they would to a single server; mongos sends each operation to the right shards and merges results.
- Config servers: a replica set storing the cluster metadata: which ranges of data live on which shard.
Shard keys and chunks: ranged vs hashed sharding
You shard a collection by a shard key, one or more fields every document has:
sh.enableSharding("shop") // optional in recent versions
db.orders.createIndex({ customerId: 1, _id: 1 })
sh.shardCollection("shop.orders", { customerId: 1, _id: 1 })MongoDB divides the key's value space into contiguous chunks (ranges), and the cluster spreads chunks across shards. Each document lives in the chunk whose range contains its key. As data grows, chunks split, and the balancer (Day 24) moves them so each shard holds a similar amount of data.
Two strategies:
| Strategy | How values map | Good for | Watch out for |
|---|---|---|---|
| Ranged | Neighboring key values in the same chunk | Range queries on the key | Monotonically increasing keys send all inserts to one chunk |
| Hashed | Hash of the key decides the chunk | Even write distribution | Range queries on the key hit all shards |
Targeted vs scatter-gather queries
mongos can only send a query to specific shards if the query includes the shard key (or a prefix of it):
db.orders.find({ customerId: 42 }) // targeted: only the shard(s) owning customer 42
db.orders.find({ status: "paid" }) // scatter-gather: every shard, results mergedScatter-gather queries get slower as you add shards, because every shard must answer. Choose the shard key so the most frequent queries include it (Day 23).
What sharding changes for applications
- Unique indexes must include the shard key (except
_id, which is unique per shard; generate globally unique ids). - Updates and deletes that target one document should include the shard key.
- Multi-document transactions work across shards but cost more.
- Since MongoDB 5.0 you can reshard a collection to a new key online, and 6.0+ can refine a key by adding suffix fields, so a poor choice is fixable, at a significant cost in time and resources.
Check yourself
It's the router for a sharded cluster. Applications connect to mongos as if it were one server; it routes each operation to the shards holding the relevant data, using chunk metadata from the config servers, and merges their results.
The query doesn't include the shard key, customerId, so mongos can't tell which shards hold matching orders. It must ask every shard and merge the results, a scatter-gather query whose cost grows with the number of shards.
When the key increases over time (like a timestamp or ObjectId) and you need writes spread evenly; ranged would send every insert to the newest chunk.
When a single replica set can't handle the data size, write throughput or working set, even after indexing and vertical scaling. Sharding adds operational complexity, so it shouldn't be the first fix.
The cluster's metadata: which chunks exist, their key ranges and which shard owns each one. They run as a replica set because the cluster can't route without them.