MongoDB Sharding

Beginner
14 min read
Updated: Oct 2026
Concept guide
Live examples

What Is MongoDB Sharding?

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.

Why Use Sharding?

ReasonWhat it helps with
Very large datasetsStore more data than one machine can hold comfortably
High throughputSpread reads and writes across shards
Storage growthAdd shards to increase capacity
Horizontal scalingGrow 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.

Horizontal Scaling vs. Vertical Scaling

ScalingBasic idea
Vertical scalingMake one server more powerful (CPU, RAM, disk)
Horizontal scalingAdd 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.

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).

How MongoDB Sharding Works

Request flow
Application
     |
     v
  mongos
     |
     | Uses shard key / routing metadata
     |
     +----------+----------+
     |          |          |
     v          v          v
  Shard 1    Shard 2    Shard 3
  1. The application sends a request to mongos.
  2. mongos determines which shard(s) may hold the data.
  3. The request goes to the appropriate shard(s).
  4. Results return through mongos.
  5. The application receives the result.

Connect to mongos for normal cluster reads and writes—not directly to a single shard.

What Is a Shard Key?

A shard key is a field or combination of fields that MongoDB uses to distribute documents across shards.

mongosh
{
  _id: 1,
  userId: 1001,
  name: "Laptop",
  price: 75000
}

// Possible shard key:
{ userId: 1 }
  • The shard key influences where documents are stored.
  • It also affects how queries can be routed.
  • Choosing a good key is critical for balance and performance.
  • A poor key can cause uneven distribution or inefficient queries.

Shard Key Example

mongosh
db.orders.insertMany([
  { userId: 101, total: 500 },
  { userId: 202, total: 800 },
  { userId: 303, total: 300 }
])

// Shard key:
{ userId: 1 }

How It Works

  1. MongoDB examines each document’s shard-key value (userId).
  2. That value determines placement within the sharded collection.
  3. Routing uses shard-key information when queries include it.
  4. Exact placement depends on strategy (ranged/hashed) and cluster state.

Chunks

MongoDB partitions sharded data into chunks—ranges of shard-key values with an inclusive lower bound and exclusive upper bound.

Chunk idea
Shard Key Range

0 ─────── 100
101 ───── 200
201 ───── 300
301 ───── 400

       ↓

     Chunks
       ↓
 distributed across shards
  • A chunk covers a range of shard-key values.
  • Chunks are distributed across shards.
  • MongoDB can move ranges between shards to balance data.

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.

Ranged Sharding vs. Hashed Sharding

Neither strategy is always better. Match the strategy to your key pattern and queries.

StrategyBasic ideaUseful characteristic
Ranged shardingDistribute by shard-key rangesTargeted range queries when the key fits
Hashed shardingDistribute by hash of the shard-key valueMore 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.

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.

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

Worked Walkthrough

Small orders collection with shard key { userId: 1 }.

Sample data
[
  { orderId: 1, userId: 101, total: 500 },
  { orderId: 2, userId: 202, total: 800 },
  { orderId: 3, userId: 101, total: 300 }
]

Shard key: { userId: 1 }
mongosh
db.orders.find({
  userId: 101
})

How It Works

  1. The query is sent to mongos.
  2. userId is the shard key.
  3. mongos uses that value to find the relevant shard(s).
  4. Only those shard(s) need to process the targeted operation.
  5. The result returns through mongos.

MongoDB Sharding Examples

Run these from mongosh connected to a mongos in a sharded cluster.

Example 1 — Enable Sharding for a Database

Starting in MongoDB 6.0, this method is not required to shard a collection. It can still explicitly create a database.

mongosh
sh.enableSharding("shop")

How It Works

  1. Run against mongos.
  2. Creates/prepares the shop database context for sharding workflows.
  3. Does not by itself shard a specific collection—use sh.shardCollection() next.

Example 2 — Shard a Collection (Ranged)

mongosh
sh.shardCollection(
  "shop.orders",
  { userId: 1 }
)

How It Works

  1. shop.orders is the full namespace (database.collection).
  2. userId is the shard key field.
  3. 1 means ranged sharding on that field.
  4. MongoDB begins distributing the collection across shards (balancer may migrate ranges).

Example 3 — Hashed Sharding

mongosh
sh.shardCollection(
  "shop.orders",
  { userId: "hashed" }
)

How It Works

  1. "hashed" tells MongoDB to shard on a hash of userId.
  2. Hashes tend to spread values more evenly than raw monotonic sequences.
  3. Range queries on userId are less likely to target a single shard.

Example 4 — Check Sharding Status

mongosh
sh.status()

How It Works

  1. Reports sharded databases, collections, shard keys, and cluster members.
  2. 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

  1. The filter includes the shard key userId.
  2. mongos can target the relevant shard(s).
  3. Avoids unnecessary work on unrelated shards when routing succeeds.

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.

Replication vs. Sharding

ReplicationSharding
Maintains copies of dataDistributes data
Uses replica setsUses multiple shards
Improves redundancy / availabilityEnables horizontal scaling
Primary / secondary modelShard / mongos / config-server architecture
Each member holds the datasetEach shard stores a subset of sharded data

MongoDB commonly uses both together: each shard is a replica set, so you get distribution and redundancy.

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.

When Should You Consider Sharding?

Consider sharding when…Also remember
Dataset outgrows a practical single serverTune indexes and queries first
Storage needs exceed one machineShards add operational cost
Workload needs horizontal scaleShard key + query patterns matter
Read/write load should be distributedNot 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.

Performance Notes

IdeaPractical tip
Shard key firstKey choice drives distribution and routing quality
Targeted queriesInclude the shard key (or compound prefix) when possible
Scatter/gatherQueries without key info may hit many shards
HotspotsUneven keys concentrate load on few shards
More shardsAdds capacity and complexity—not a free speed boost
Ranged vs hashedTrade even distribution against range-query targeting

Cheat Sheet

ConceptRemember
ShardingDistributes data across multiple machines
Horizontal scalingAdd machines to increase capacity
ShardHolds a subset of sharded data (as a replica set)
mongosRoutes client operations
Config serverStores cluster metadata / configuration
Shard keyDetermines distribution and routing
ChunkRange of shard-key values
BalancerMigrates ranges to maintain distribution
Ranged shardingDistributes by shard-key ranges
Hashed shardingDistributes using hashed key values
Targeted queryRouted to relevant shard(s)
Scatter/gatherQueries multiple shards

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.

Next: Aggregation Stages

Learn the pipeline stages used to filter, group, and reshape data.

Stages tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful