MongoDB Sharding

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 5 Examples
Scaling

What You’ll Learn

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.

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.

🏗️ Sharded cluster components

ComponentRoleConnect from app?
mongosQuery router; parses operations and targets the right shard(s)Yes — this is your connection string endpoint
ShardReplica set holding a portion of sharded collection dataNo — apps go through mongos
Config serversStore chunk ranges, shard map, and cluster metadataNo — internal to the cluster
BalancerBackground process that migrates chunks for even distributionN/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.

📝 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 mongossh.* 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.
mongosh
// Connect: mongosh "mongodb://mongos-host:27017"

sh.enableSharding("shop");
sh.shardCollection("shop.orders", { orderId: "hashed" });
sh.status(true);

⚡ Quick Reference

TaskCommand
Enable sharding on DBsh.enableSharding("mydb")
Shard collection (hashed)sh.shardCollection("mydb.orders", { orderId: "hashed" })
Shard collection (ranged)sh.shardCollection("mydb.events", { region: 1, ts: 1 })
Cluster overviewsh.status()
Detailed chunk infosh.status(true)
Balancer statesh.getBalancerState()
Hashed key
{ userId: "hashed" }

Even write distribution

Compound ranged
{ region: 1, ts: 1 }

Geo/time range queries

Connect string
mongodb://mongos1,mongos2/

App targets routers

Chunk default
~128 MB per chunk

Balancer splits/migrates

🧰 Key concepts

Terms you will see in docs, logs, and sh.status() output:

shard key Required

Indexed field(s) that determine document placement. Every query should ideally include the shard key (or its prefix) for targeted routing.

{ customerId: 1, orderDate: 1 }
{ sessionId: "hashed" }
chunk Core

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
mongos Router

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 scatter Query 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.

// Targeted:
{ userId: "U42" }
// Scatter:
{ status: "open" }

Examples Gallery

An e-commerce shop.orders collection—enable sharding, pick keys, and verify cluster health. Commands assume a connected mongos shell.

📚 Getting Started

Sample orders and the database context before sharding.

Example 1 — Sample orders collection

mongosh
use shop;

db.orders.insertMany([
  { orderId: "ORD-1001", customerId: "C10", region: "US", amount: 49.99, createdAt: ISODate("2025-06-01") },
  { orderId: "ORD-1002", customerId: "C22", region: "EU", amount: 120.00, createdAt: ISODate("2025-06-02") },
  { orderId: "ORD-1003", customerId: "C10", region: "US", amount: 15.50, createdAt: ISODate("2025-06-03") },
  { orderId: "ORD-1004", customerId: "C88", region: "APAC", amount: 300.00, createdAt: ISODate("2025-06-04") }
]);

// Index before sharding (required)
db.orders.createIndex({ orderId: 1 });

How It Works

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();

How It Works

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 */

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 */

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();

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.

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

📝 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.
  • Previous topic: Replication. Next: Aggregation Stages.

Conclusion

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

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about sharding

Use these points when planning horizontal scale for MongoDB.

5
Core concepts
🔑 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.

Continue the MongoDB Series

Understand horizontal scaling with sharding, then explore aggregation pipeline stages.

Next: Aggregation Stages →

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.

5 people found this page helpful