Sharding lets MongoDB spread a large collection across multiple machines so no single server holds all the data or handles all the traffic. This guide explains the architecture, how to choose a shard key, and the admin commands you run from mongos.
01
Horizontal scale
Split data across shards.
02
Cluster parts
mongos, config, shards.
03
Shard keys
Pick keys that distribute load.
04
Chunks & balancer
How data moves between shards.
05
Admin commands
Enable and shard collections.
06
When to shard
Replica set vs sharded cluster.
Fundamentals
Definition and Usage
Sharding is MongoDB’s approach to horizontal scaling: instead of making one server bigger (vertical scaling), you add more servers and partition data so each shard stores a subset of documents.
💡
Beginner tip
Your application connects to mongos—not directly to individual shard servers. The router figures out which shard(s) hold the data for each query, much like a load balancer with a map of where every chunk lives.
Each shard is usually a replica set (primary + secondaries) for high availability. A sharded cluster also includes config servers (cluster metadata) and one or more mongos routers. On MongoDB Atlas, you can enable sharding on a cluster without managing these components yourself.
Sharding is an operational scaling topic—distinct from aggregation pipeline stages or query operators, but essential when datasets outgrow a single replica set.
Architecture
🏗️ Sharded cluster components
Component
Role
Connect from app?
mongos
Query router; parses operations and targets the right shard(s)
Yes — this is your connection string endpoint
Shard
Replica set holding a portion of sharded collection data
No — apps go through mongos
Config servers
Store chunk ranges, shard map, and cluster metadata
No — internal to the cluster
Balancer
Background process that migrates chunks for even distribution
N/A — runs automatically on the cluster
A typical flow: the app sends find({ userId: "U42" }) to mongos → mongos consults config metadata → routes the query to the shard owning the chunk where userId: "U42" lives → returns merged results to the client.
Foundation
📝 Syntax
Sharding setup runs on a mongos connection with cluster admin privileges. The two core steps are enabling sharding on a database, then sharding a collection with a shard key:
mongosh
// 1) Enable sharding on a database
sh.enableSharding("<database>");
// 2) Shard a collection with a shard key index
sh.shardCollection(
"<database>.<collection>",
{ <shardKeyField>: 1 } // ranged (ascending)
// { <shardKeyField>: "hashed" } // hashed
);
// 3) Inspect cluster state
sh.status();
Syntax Rules
Run on mongos — sh.* helpers are unavailable on a standalone mongod.
Shard key index required — the collection must have an index that starts with the shard key fields before sh.shardCollection.
Immutable choice — the shard key cannot be changed on a sharded collection; plan before sharding.
Hashed vs ranged — hashed keys spread writes evenly; ranged keys preserve range queries on the prefix.
Unique indexes — must include the shard key as a prefix (except _id alone on non-sharded collections).
Empty or small collections — easiest to shard before heavy traffic; large live migrations need more planning.
A contiguous range of shard key values assigned to one shard. When a chunk grows too large, MongoDB splits it; the balancer moves chunks to equalize storage.
Key range: [MinKey, 500)
Shard: shardA
mongosRouter
Stateless query router. Deploy multiple mongos instances behind a load balancer for high availability—clients never connect to shard primaries directly.
mongosh mongodb://mongos:27017
targeted vs scatterQuery type
Targeted queries include the shard key and hit one or few shards. Scatter-gather queries lack the key and must ask every shard—slower at scale.
Each order has a unique orderId—a strong candidate for a hashed shard key because order IDs are high-cardinality and writes should spread evenly across shards.
Example 2 — Enable sharding on the database
mongosh
// Run on mongos with clusterAdmin role
sh.enableSharding("shop");
/* MongoDB marks the shop database as sharding-enabled.
Individual collections are sharded separately next. */
sh.status();
sh.enableSharding is a prerequisite—it tells the cluster the shop database may contain sharded collections. It does not move data by itself.
📈 Practical Patterns
Hashed vs ranged shard keys and monitoring the cluster.
Example 3 — Shard with a hashed key (even writes)
mongosh
// Hashed keys distribute inserts across shards
sh.shardCollection("shop.orders", { orderId: "hashed" });
// Targeted lookup by full shard key
db.orders.find({ orderId: "ORD-1002" });
/* orderId values hash to different chunks →
writes spread evenly; ideal for UUID/order-id workloads */
📤 Result:
Collection shop.orders sharded.
Chunks distributed across shardA, shardB, ...
How It Works
Hashed sharding uses a hash of the field value—not the raw value—for chunk boundaries. That prevents a monotonic key (like auto-increment IDs) from funneling all new writes to one shard.
Example 4 — Ranged compound shard key (region + time)
For analytics filtered by region and date range, a compound ranged key keeps related data together:
mongosh
// New collection — choose key BEFORE sharding
db.events.createIndex({ region: 1, createdAt: 1 });
sh.shardCollection("shop.events", { region: 1, createdAt: 1 });
// Targeted query (uses shard key prefix)
db.events.find({
region: "US",
createdAt: { $gte: ISODate("2025-06-01"), $lt: ISODate("2025-07-01") }
});
/* mongos routes to shard(s) owning US + June chunks only */
📤 Benefit:
Range queries on { region, createdAt }
→ targeted shard routing (not scatter-gather)
How It Works
Ranged keys excel when queries include the key prefix. Watch for low-cardinality leading fields (e.g. only 3 regions)—they can create hot shards if one region dominates traffic.
Example 5 — Inspect cluster with sh.status()
mongosh
sh.status(true);
sh.getBalancerState(); // true when balancer migrates chunks
sh.isBalancerRunning(); // in-progress migration check
// Per-collection chunk distribution
use config;
db.chunks.find({ ns: "shop.orders" }).countDocuments();
📤 What to look for:
• Each shard listed with replica set members
• Chunk counts roughly balanced
• Balancer enabled (unless maintenance window)
• No jumbo chunks blocking splits
How It Works
Regular sh.status() checks belong in your runbook. Imbalanced chunk counts or disabled balancers often explain uneven disk use or slow queries before you blame application code.
Compare
📋 Sharding vs related scaling options
Approach
Scales
Complexity
Best for
Single mongod
One machine
Low
Local dev, tiny apps
Replica set
HA + read scaling
Medium
Most production workloads
Sharded cluster
Storage + write throughput
High
Very large datasets, high QPS
Hashed shard key
Even writes
Medium
High-cardinality IDs, uniform access
Ranged shard key
Range query locality
Medium
Geo/time/reporting with key in query
Atlas M30+ sharded
Managed horizontal scale
Lower ops burden
Teams avoiding self-hosted mongos
🧠 How Sharding Works
1
App connects to mongos
The driver sends reads and writes to a mongos router, not individual shards.
Client
2
Metadata lookup
mongos reads the chunk map from config servers to learn which shard owns each key range.
Config
3
Targeted or scatter routing
Queries with the shard key hit specific shards; others fan out to all shards and merge results.
Route
4
Chunks split & migrate
When chunks grow large, they split; the balancer moves chunks between shards to stay balanced.
Balance
=
📈
Horizontal capacity
Add shards to grow storage and throughput without one giant server.
Important
📝 Notes
Shard key is permanent for a sharded collection—design and load-test before production sharding.
Monotonic keys (auto-increment, timestamps alone) on ranged sharding can create a hot shard; prefer hashed keys or compound keys with high-cardinality leading fields.
Scatter-gather queries without the shard key do not scale linearly—every shard must participate.
Each shard is a replica set—sharding adds scale; replication within each shard adds failover.
Transactions across many shards are supported but have higher overhead than single-shard transactions.
Atlas handles mongos, config servers, and balancer for you on sharded tiers—ideal for learning without building a full cluster locally.
Sharding partitions data across shards so MongoDB scales horizontally when replica sets alone are not enough. Success depends on choosing a good shard key, connecting through mongos, and writing queries that target specific chunks whenever possible.
Most beginners should master replica sets, indexes, and aggregation first. When metrics demand sharding, enable it on a database, shard collections deliberately, and monitor with sh.status().
Pick shard keys with high cardinality and even write distribution
Include the shard key (or prefix) in your most frequent queries
Shard before the collection reaches terabyte scale if you know you will need it
Run sh.status() after deploys and during capacity reviews
Use hashed keys for UUID / random ID workloads with uniform access
Keep each shard as a healthy replica set with monitored replication lag
❌ Don’t
Shard prematurely—optimize indexes and queries on a replica set first
Use a low-cardinality field alone (e.g. status: "active") as the only shard key
Connect applications directly to shard primaries—always use mongos
Assume you can change the shard key later without a migration project
Ignore jumbo chunks—they block splits and prevent balancing
Run sh.shardCollection on a standalone mongod without a full cluster
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about sharding
Use these points when planning horizontal scale for MongoDB.
5
Core concepts
📈01
Horizontal scale
Data split across shards.
Basics
🔑02
Shard key
Controls placement.
Design
🛠03
mongos
App connection point.
Router
📦04
Chunks
Balancer keeps balance.
Ops
⚠️05
Plan first
Keys are hard to change.
Caution
❓ Frequently Asked Questions
Sharding splits a large collection across multiple servers (shards) so read and write load is distributed horizontally. Each shard is typically a replica set. Applications connect to mongos routers, which route queries to the correct shard(s) using metadata stored on config servers.
Shard when a single replica set cannot meet storage or throughput needs after tuning indexes, queries, and hardware. Most small and medium apps never need sharding—replica sets plus good schema design are enough. Atlas can scale a cluster to sharded mode when metrics justify it.
The shard key is an indexed field (or compound fields) that determines which shard owns each document. MongoDB divides the key range into chunks and migrates chunks between shards to balance data. Choose a key with high cardinality and even distribution—poor keys cause hot shards.
mongos is the query router your application connects to instead of individual shards. Config servers store the cluster metadata map—which chunks live on which shards. Together with shard replica sets, they form a sharded cluster.
You cannot change the shard key on an existing sharded collection in place. Plan the key carefully before sh.shardCollection. If requirements change, you may need to migrate data to a new sharded collection with a different key.
Replication (replica sets) copies the same data for high availability and read scaling. Sharding partitions data across shards for horizontal capacity. Production sharded clusters use replica sets for each shard—combining both for scale and resilience.
Did you know?
MongoDB’s balancer runs in the background and migrates chunks between shards when data distribution becomes uneven—you do not manually move documents. A jumbo chunk exceeds the max chunk size and cannot split until you resolve the underlying key distribution issue. See the official sharding documentation.