Problem Statement
What is sharding in MongoDB?
Explanation
Sharding is MongoDB's approach to horizontal scaling by distributing data across multiple servers or clusters. It partitions large datasets into smaller, more manageable pieces called shards, with each shard holding a subset of the data.
Sharding allows MongoDB to handle datasets and throughput requirements that exceed the capacity of a single server. As your data grows, you can add more shards to distribute the load, enabling virtually unlimited scalability. This is fundamentally different from vertical scaling, which involves upgrading a single server's hardware.
Code Solution
SolutionRead Only
// Enable sharding on database
sh.enableSharding("myDatabase")
// Shard a collection
sh.shardCollection(
"myDatabase.users",
{ userId: 1 } // Shard key
)
// Data distributed across shards:
// Shard 1: userId 1-1000
// Shard 2: userId 1001-2000
// Shard 3: userId 2001-3000