Sharding in MongoDB — MongoDB Technical Interview Questions & Answers

Horizontally partitioning data across multiple servers.

Sharding in MongoDB

  • Simple meaning: Sharding splits one big collection across several machines (shards) using a shard key.
  • mongos is the router: your app talks to mongos, which sends the query to the right shard(s).
  • How to use: you need this only at huge scale. For college projects, one replica set (Atlas M0) is enough.
  • Good shard key: high cardinality, even spread (not “country: IN” for all rows).
  • Common mistake: sharding a tiny database “for speed”. Extra complexity, little gain.
  • Interview tip: Horizontal scale. Shard key. mongos. Contrast with replica set (copies vs split).

Technical Interview Tip: Sharding = split. Replica = copy. Name mongos.

Code Examples for Sharding in MongoDB

Sharding in MongoDB — working example

// Replica set: primary takes writes; secondaries replicate.
rs.status()

// Sharding: data partitioned by shard key across shards
sh.status()
sh.shardCollection("prep_pilot.orders", { customerId: "hashed" })
db.orders.find({ customerId: 42 })

Sharding in MongoDB — replica sets give HA; sharding scales writes/data horizontally via a shard key.

How to Explain Sharding in MongoDB to an Interviewer

Sharding vs replica set?

Shard splits data Replica copies data