0
0
MongoDBquery~5 mins

Horizontal scaling mental model in MongoDB

Choose your learning style9 modes available
Introduction

Horizontal scaling means adding more machines to handle more data or users. It helps systems grow smoothly without slowing down.

When your database grows too big for one server to handle.
When many users access your app at the same time and one server gets overloaded.
When you want to avoid downtime by spreading data across multiple servers.
When you want to improve read and write speeds by dividing the work.
When you want to easily add more servers as your app becomes popular.
Syntax
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.

Examples
This enables sharding on the shopDB database and shards the orders collection by orderId.
MongoDB
sh.enableSharding("shopDB")
sh.shardCollection("shopDB.orders", { orderId: 1 })
This sets up horizontal scaling for user profiles by splitting data based on userId.
MongoDB
sh.enableSharding("userDB")
sh.shardCollection("userDB.profiles", { userId: 1 })
Sample Program

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.

MongoDB
/* 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 */
OutputSuccess
Important Notes

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.

Summary

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.