Sharding distributes data across multiple machines. MongoDB uses it for very large datasets and high-throughput workloads that outgrow a single server.
Idea
One server
↓
Limited storage / CPU / workload capacity
Multiple shards
↓
Data + workload distributed across servers
Instead of only making one server bigger, distribute the workload across multiple servers—horizontal scaling.
Motivation
Why Use Sharding?
Reason
What it helps with
Very large datasets
Store more data than one machine can hold comfortably
High throughput
Spread reads and writes across shards
Storage growth
Add shards to increase capacity
Horizontal scaling
Grow by adding machines, not only bigger hardware
Sharding adds infrastructure and operational complexity. If a dataset fits comfortably on a single server (or a single replica set), an unsharded deployment may be the better choice.
Compare
Horizontal Scaling vs. Vertical Scaling
Scaling
Basic idea
Vertical scaling
Make one server more powerful (CPU, RAM, disk)
Horizontal scaling
Add more servers and distribute the workload
Visual
Vertical Scaling
Bigger Server
┌───────────────┐
│ More CPU │
│ More RAM │
│ More Storage │
└───────────────┘
Horizontal Scaling
Server 1 Server 2 Server 3
↓ ↓ ↓
Data A Data B Data C
MongoDB sharding is horizontal scaling: each shard handles a subset of the data and work.
Architecture
What Is a Sharded Cluster?
A sharded cluster has three core pieces: shards, mongos routers, and config servers.
Sharded cluster
Application
|
v
mongos
Query Router
/ | \
v v v
Shard 1 Shard 2 Shard 3
/ | \
Replica Replica Replica
Set Set Set
Config Servers
|
v
Cluster Metadata
Shards
Each shard stores a subset of the sharded data. Each shard must be deployed as a replica set for redundancy and availability.
mongos
mongos is the query router between applications and the cluster. Clients should connect to mongos for cluster-level operations.
Config servers
Config servers store cluster metadata and configuration that mongos uses for routing. They are deployed as a replica set (CSRS).
Approach
How MongoDB Sharding Works
Request flow
Application
|
v
mongos
|
| Uses shard key / routing metadata
|
+----------+----------+
| | |
v v v
Shard 1 Shard 2 Shard 3
The application sends a request to mongos.
mongos determines which shard(s) may hold the data.
The request goes to the appropriate shard(s).
Results return through mongos.
The application receives the result.
Connect to mongos for normal cluster reads and writes—not directly to a single shard.
Critical
What Is a Shard Key?
A shard key is a field or combination of fields that MongoDB uses to distribute documents across shards.
MongoDB can move ranges between shards to balance data.
Balance
Balancer
The balancer runs in the background and migrates ranges between shards to help keep data appropriately distributed.
Balancer idea
Before balancing:
Shard 1 → Many chunks
Shard 2 → Few chunks
Shard 3 → Few chunks
↓
Balancer
↓
Shard 1 → Balanced
Shard 2 → Balanced
Shard 3 → Balanced
Balancing is continuous background work—not an instant, perfect rearrange after every write.
Strategies
Ranged Sharding vs. Hashed Sharding
Neither strategy is always better. Match the strategy to your key pattern and queries.
Strategy
Basic idea
Useful characteristic
Ranged sharding
Distribute by shard-key ranges
Targeted range queries when the key fits
Hashed sharding
Distribute by hash of the shard-key value
More even distribution for suitable keys (e.g. monotonic)
Ranged sharding
Ranges
userId 1–1000
userId 1001–2000
userId 2001–3000
Nearby values are more likely to share a range/chunk.
Hashed sharding
Hash flow
userId
↓
Hash
↓
Hash value
↓
Distribution across ranges
Hashed sharding can spread monotonically changing values more evenly, but range queries on the shard key are less likely to target a single shard.
Routing
Targeted Queries vs. Scatter/Gather Queries
Targeted query
The query includes the shard key (or an appropriate prefix of a compound shard key).
mongosh
db.orders.find({
userId: 101
})
// mongos can route to relevant shard(s)
mongos
|
+----> relevant shard(s)
Scatter/gather
The query does not provide enough shard-key information, so mongos may need to query multiple or all shards and combine results.
mongosh
db.orders.find({
total: { $gt: 500 }
})
// often needs work across many shards
mongos
/ | \
v v v
Shard 1 Shard 2 Shard 3
Exact routing depends on the query shape and metadata. The key lesson: include the shard key when you can to help targeting.
Think
Pseudocode
Pseudocode
Application sends query
↓
mongos receives query
↓
Check shard-key information
↓
Can the query be targeted?
/ \
Yes No
↓ ↓
Target shard Query multiple shards
↓ ↓
Combine result
↓
Return result
Trace
Worked Walkthrough
Small orders collection with shard key { userId: 1 }.
"hashed" tells MongoDB to shard on a hash of userId.
Hashes tend to spread values more evenly than raw monotonic sequences.
Range queries on userId are less likely to target a single shard.
Example 4 — Check Sharding Status
mongosh
sh.status()
How It Works
Reports sharded databases, collections, shard keys, and cluster members.
Use it to verify configuration after sharding—not as an application API.
Example 5 — Targeted Query
mongosh
db.orders.find({
userId: 101
})
How It Works
The filter includes the shard key userId.
mongos can target the relevant shard(s).
Avoids unnecessary work on unrelated shards when routing succeeds.
Locality
Zones
Zones associate ranges of shard-key values with specific shards. They can improve data locality (for example across data centers). Zone ranges use inclusive lower and exclusive upper bounds, based on the shard key.
This page only introduces the idea—zone setup belongs on a dedicated guide.
Compare
Replication vs. Sharding
Replication
Sharding
Maintains copies of data
Distributes data
Uses replica sets
Uses multiple shards
Improves redundancy / availability
Enables horizontal scaling
Primary / secondary model
Shard / mongos / config-server architecture
Each member holds the dataset
Each shard stores a subset of sharded data
MongoDB commonly uses both together: each shard is a replica set, so you get distribution and redundancy.
Terminology
Sharding vs. Partitioning
In MongoDB, sharding partitions a collection’s documents across multiple shards based on a shard key. Think “split the collection across machines using a key,” not a separate product feature from sharding.
Guidance
When Should You Consider Sharding?
Consider sharding when…
Also remember
Dataset outgrows a practical single server
Tune indexes and queries first
Storage needs exceed one machine
Shards add operational cost
Workload needs horizontal scale
Shard key + query patterns matter
Read/write load should be distributed
Not every query becomes faster
There is no universal data-size threshold. Workload, hardware, query patterns, storage, and growth all matter. Small datasets that fit one server often gain little from sharding.
Edge Cases & Pitfalls
Common beginner mistakes around MongoDB sharding.
key
Poor shard key
Uneven load, hotspots, and hard-to-target queries often start with a weak key choice.
monotonic
Monotonic keys without a plan
Rising keys (like timestamps) can concentrate writes. Consider hashed sharding or a better compound key.
speed
Sharding ≠ automatic speed
Scatter/gather queries and bad keys can make things worse. Sharding is about capacity and scale, not magic latency.
connect
Do not connect apps to a single shard
Use mongos for normal cluster operations so routing and metadata stay correct.
vs
Sharding ≠ replication
Replication copies; sharding distributes. You usually need both in a sharded cluster.
balancer
Balancer is not instant perfection
Migrations take time and resources. Do not expect perfect balance after every insert.
strategy
Hashed is not always better
Hashed helps some distributions; ranged helps some range queries. Pick based on access patterns.
Analysis
Performance Notes
Idea
Practical tip
Shard key first
Key choice drives distribution and routing quality
Targeted queries
Include the shard key (or compound prefix) when possible
Scatter/gather
Queries without key info may hit many shards
Hotspots
Uneven keys concentrate load on few shards
More shards
Adds capacity and complexity—not a free speed boost
Ranged vs hashed
Trade even distribution against range-query targeting
Reference
Cheat Sheet
Concept
Remember
Sharding
Distributes data across multiple machines
Horizontal scaling
Add machines to increase capacity
Shard
Holds a subset of sharded data (as a replica set)
mongos
Routes client operations
Config server
Stores cluster metadata / configuration
Shard key
Determines distribution and routing
Chunk
Range of shard-key values
Balancer
Migrates ranges to maintain distribution
Ranged sharding
Distributes by shard-key ranges
Hashed sharding
Distributes using hashed key values
Targeted query
Routed to relevant shard(s)
Scatter/gather
Queries multiple shards
Remember
Key Takeaways
Sharding distributes data across machines for horizontal scale.
A cluster needs shards, mongos, and config servers.
Each shard is a replica set—sharding and replication work together.
The shard key decides distribution and strongly affects query routing.
Chunks are shard-key ranges; the balancer migrates them over time.
Ranged vs hashed, targeted vs scatter/gather—choose based on access patterns.
One line: Sharding splits a collection across shard replica sets; mongos routes with the shard key, and a good key is the difference between scale and pain.
Frequently Asked Questions
Sharding distributes a collection's data across multiple machines (shards) so large datasets and high-throughput workloads can scale horizontally. Applications connect through mongos routers, which use cluster metadata from config servers.
A single server has practical limits for CPU, RAM, storage, and I/O. Sharding divides data and load across servers so you can add capacity by adding machines.
A shard stores a subset of the sharded data. Each shard must be deployed as a replica set, so a sharded cluster combines horizontal distribution with replication.
A shard key is a field or compound fields that MongoDB uses to distribute documents across shards. It also influences how mongos can route queries. A poor key can cause uneven load or inefficient queries.
mongos is the query router between client applications and the sharded cluster. Clients should connect to mongos for cluster-level reads and writes, not directly to a single shard.
Config servers store metadata and configuration for the sharded cluster—information mongos needs to route operations. They are deployed as a replica set (CSRS).
Replication keeps copies of the same data for redundancy and availability. Sharding distributes subsets of data across shards for horizontal scale. Production sharded clusters use both: each shard is a replica set.
Ranged sharding places nearby shard-key values in the same ranges, which can help targeted range queries. Hashed sharding hashes the key for more even distribution of some key patterns, but range queries on the key are less likely to hit a single shard.
A chunk is a range of shard-key values (inclusive lower bound, exclusive upper bound). Chunks are distributed across shards, and MongoDB can migrate ranges to balance data.
The balancer runs in the background and migrates ranges between shards to help keep sharded data appropriately distributed across the cluster.
A query that includes the shard key (or an appropriate prefix of a compound shard key) so mongos can send work to the relevant shard or set of shards instead of every shard.
When a query lacks enough shard-key information, mongos may need to query multiple or all shards and combine the results. These broadcast-style operations can be more expensive.
Not automatically. Sharding can improve scalability for large data and high throughput when the shard key and query patterns fit. Poor keys, scatter/gather queries, or unnecessary complexity can hurt performance.
No. If a dataset fits comfortably on a single server (or a single replica set), sharding may add complexity for little benefit. Consider workload, growth, storage, and operations before sharding.
Yes, with care. Starting in MongoDB 5.0 you can reshard a collection to change its shard key, and you can refine a key by adding suffix fields. Resharding is an operational process—choose the initial key thoughtfully.