Horizontal scaling means adding more machines to handle more data or users. It helps systems grow smoothly without slowing down.
Horizontal scaling mental model in MongoDB
sh.enableSharding("databaseName") sh.shardCollection("databaseName.collectionName", { shardKey: 1 })
Use sh.enableSharding to turn on sharding for a database.
Use sh.shardCollection to split a collection using a shard key.
shopDB database and shards the orders collection by orderId.sh.enableSharding("shopDB") sh.shardCollection("shopDB.orders", { orderId: 1 })
userId.sh.enableSharding("userDB") sh.shardCollection("userDB.profiles", { userId: 1 })
This example shows how to set up horizontal scaling in MongoDB by adding servers as shards, enabling sharding on a database, choosing a shard key, and letting MongoDB distribute data automatically. Queries are routed to the correct server based on the shard key.
/* Step 1: Add shards (servers) to the cluster */ sh.addShard("server1:27017") sh.addShard("server2:27017") /* Step 2: Enable sharding on the database */ sh.enableSharding("ecommerceDB") /* Step 3: Choose a shard key and shard the collection */ sh.shardCollection("ecommerceDB.products", { productId: 1 }) /* Step 4: MongoDB automatically distributes data based on productId */ /* Step 5: When a query comes in, MongoDB routes it to the right shard */
Choosing the right shard key is very important for balanced data distribution.
Too many writes to one shard can cause a hotspot and slow down the system.
MongoDB manages routing and balancing automatically once sharding is set up.
Horizontal scaling means adding more servers to share the load.
MongoDB uses sharding to split data across servers based on a shard key.
This helps handle more data and users without slowing down.