How does sharding work in MongoDB and why is it used?
Learn how MongoDB sharding partitions data across shards with a shard key, mongos routers and config servers to scale storage and throughput horizontally.
Expected Interview Answer
Sharding is MongoDB's method of horizontal scaling: it partitions a collection's documents across multiple servers (shards) using a shard key, so no single machine has to hold all the data or serve all the traffic.
A sharded cluster has three parts: shards (each a replica set holding a subset of data), config servers (which store cluster metadata and the chunk-to-shard mapping), and mongos routers (which clients connect to and which route queries to the right shards). MongoDB groups documents into chunks by shard-key range and a balancer migrates chunks between shards to keep them even. Queries that include the shard key are targeted to specific shards, while queries without it must be broadcast (scatter-gather) to all shards.
- Scales storage and throughput horizontally beyond one machine
- Distributes read and write load across many servers
- Keeps working data set in RAM per shard
- Targeted queries touch only relevant shards
- Grows capacity by adding shards without downtime
AI Mentor Explanation
Think of one scorer trying to record every match in a nationwide tournament happening in ten cities at once — impossible. Instead you assign one scorer per city, and a central fixtures desk knows which city each match is in. Sharding works the same way: the shard key is like the city, each shard is a local scorer holding only its matches, config servers are the fixtures desk, and the mongos router sends each query straight to the scorer who owns that game.
Step-by-Step Explanation
Step 1
Enable sharding
Run sh.enableSharding('mydb') so a database becomes eligible for sharded collections.
Step 2
Choose a shard key
Pick a field (or compound fields) with high cardinality and even access, e.g. sh.shardCollection('mydb.orders', { customerId: 'hashed' }).
Step 3
Chunk the data
MongoDB divides documents into chunks by shard-key range and assigns each chunk to a shard.
Step 4
Route via mongos
Clients connect to mongos, which uses config-server metadata to send each query to the shard(s) that own the relevant chunks.
Step 5
Balance automatically
The balancer migrates chunks between shards as data grows so load and storage stay even.
What Interviewer Expects
- Definition of horizontal scaling vs vertical scaling
- Roles of shards, config servers, and mongos
- Importance of shard-key choice (cardinality, distribution)
- Difference between targeted and scatter-gather queries
- Awareness of the balancer and chunk migration
Common Mistakes
- Confusing sharding (horizontal partitioning) with replication
- Choosing a low-cardinality or monotonically increasing shard key
- Thinking mongos stores data rather than routing
- Forgetting that queries without the shard key hit every shard
- Believing a shard key can be changed freely after the fact
Best Answer (HR Friendly)
“Sharding is how MongoDB spreads a large dataset across several servers instead of cramming it onto one. Each server holds a slice of the data, and a router sends every request to the right slice, so the system can store more and handle more traffic than a single machine ever could.”
Code Example
// Connect to a mongos router, then:
sh.enableSharding('shop')
// Shard the orders collection on a hashed customerId for even distribution
sh.shardCollection('shop.orders', { customerId: 'hashed' })
// Inspect how data is distributed
sh.status()Follow-up Questions
- What makes a good shard key and why does cardinality matter?
- What is the difference between ranged and hashed sharding?
- How does a scatter-gather query differ from a targeted query?
- What role do config servers play in a sharded cluster?
- Can you change a shard key after sharding a collection?
MCQ Practice
1. Which component routes client queries to the correct shard?
mongos is the query router; clients connect to it and it uses config-server metadata to direct queries to the right shards.
2. A query that does NOT include the shard key will typically be a?
Without the shard key, mongos cannot know which shard holds the data, so it broadcasts the query to all shards and merges results.
3. What is the primary purpose of sharding?
Sharding partitions data across servers to scale horizontally; redundancy/high availability is provided by replica sets.
Flash Cards
What is a shard? — A single server (usually a replica set) that holds a subset of a sharded collection's data.
What do config servers store? — Cluster metadata: the mapping of chunks (shard-key ranges) to shards.
What does mongos do? — Routes client queries to the appropriate shards using config metadata; stores no data itself.
What is the balancer? — A background process that migrates chunks between shards to keep data evenly distributed.