What is sharding in MongoDB?

IntermediateConceptMongoDB
Answer

Short answer

Sharding splits a large collection across several replica sets (shards) so data and load are spread horizontally. A shard key decides which shard each document lives on; mongos routers send queries to the right shards, and config servers store the cluster metadata.

Architecture

App ──▶ mongos (router) ──▶ Shard A (replica set)   orders with customerId hash range 1
                       ├──▶ Shard B (replica set)   range 2
                       └──▶ Shard C (replica set)   range 3
              config servers (replica set) hold the chunk → shard map

Enabling it

sh.enableSharding("shop")
sh.shardCollection("shop.orders", { customerId: "hashed" })
sh.status()

Choosing a shard key (most important decision)

Good shard key Bad shard key
High cardinality (many values) Few values (status)
Even distribution (hashed id) Monotonic values (timestamp) → all inserts hit one shard
Used in most queries Rarely in queries → every query hits all shards

When to shard

When one replica set can't handle the data size or write throughput. Sharding adds operational complexity, so scale vertically and optimise first.

What to say in the interview

"Sharding partitions a collection across replica sets by a shard key, with mongos routing and config servers holding metadata. The shard key must have high cardinality, distribute writes evenly and appear in common queries — monotonic keys like timestamps create a hot shard."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MongoDB basics

More on MongoDB