How to shard a MongoDB collection for horizontal scale
Shard a MongoDB collection through mongos: enable sharding, choose a high-cardinality shard key, shard with a supporting index, and verify even chunk distribution via the balancer.
What and why
Sharding spreads a collection's data and load across multiple servers, letting MongoDB scale beyond one machine. The shard key determines how documents distribute, so choosing it well is the most important decision. This tutorial shards a collection on an existing cluster and verifies balanced distribution.
Prerequisites
- A sharded cluster: at least one shard (replica set), a config server replica set, and a
mongosrouter. - Admin credentials.
- A clear view of your most common queries.
Steps
1. Connect through mongos
Always operate on a sharded cluster through the router:
mongosh "mongodb://mongos-host:27017"
2. Enable sharding on the database
sh.enableSharding("shop")
3. Choose a shard key
A good shard key has high cardinality, even write distribution, and appears in your common queries. Avoid monotonically increasing keys (like raw timestamps) alone, which create a hotspot. A hashed key spreads writes evenly; a compound key can balance distribution with query targeting.
4. Shard the collection
Create a supporting index, then shard:
db.orders.createIndex({ customerId: "hashed" })
sh.shardCollection("shop.orders", { customerId: "hashed" })
5. Load and observe balancing
Insert representative data. MongoDB splits the collection into chunks and the balancer moves them across shards over time. Confirm the balancer is on:
sh.getBalancerState()
6. Verify distribution
db.orders.getShardDistribution()
This reports document and size counts per shard; they should be roughly even.
Verification
sh.status() shows shards, chunks, and balancer activity. getShardDistribution() should show data spread across shards rather than concentrated on one. Targeted queries that include the shard key should route to a single shard.
Next Steps
Monitor for jumbo chunks and unbalanced shards, refine the shard key choice in a new collection if writes skew, and use zones to pin data to specific shards for locality or compliance.
Prerequisites
- A MongoDB sharded cluster with config servers and mongos
- Admin access
- Knowledge of query patterns
Steps
- 1Connect through mongos
- 2Enable sharding on the database
- 3Choose a shard key
- 4Shard the collection
- 5Load and observe balancing
- 6Verify distribution