Problem Statement
Explain horizontal scalability in MongoDB and how it differs from vertical scalability.
Explanation
Horizontal scalability means adding more servers to distribute the load and data across multiple machines. MongoDB achieves this through sharding, where data is partitioned across multiple shards, and each shard holds a subset of the data. This allows MongoDB to handle larger datasets and higher throughput by spreading the work across many servers.
Vertical scalability means upgrading a single server with more powerful hardware like adding more CPU, RAM, or faster disks. While vertical scaling is simpler, it has limits and becomes very expensive.
Horizontal scaling is more cost-effective and has virtually no upper limit. MongoDB is designed for horizontal scaling, making it ideal for applications that need to grow beyond what a single server can handle.
Code Solution
SolutionRead Only
// Horizontal scaling example
// Data distributed across 3 shards:
// Shard 1: users with _id 1-1000
// Shard 2: users with _id 1001-2000
// Shard 3: users with _id 2001-3000
// Query automatically routed to correct shard
db.users.find({ _id: 1500 })
// MongoDB routes to Shard 2