0
0
MongoDBquery~30 mins

Why sharding is needed in MongoDB - See It in Action

Choose your learning style9 modes available
Why Sharding is Needed in MongoDB
📖 Scenario: You are managing a growing online store database using MongoDB. As the number of products and customers increases, the database starts to slow down and struggles to handle all the data efficiently.
🎯 Goal: Understand why sharding is needed by creating a simple MongoDB collection and simulating the setup for sharding to distribute data across multiple servers.
📋 What You'll Learn
Create a MongoDB collection called products with sample product documents
Define a shard key configuration variable
Write a command to enable sharding on the products collection using the shard key
Add the final command to verify sharding status
💡 Why This Matters
🌍 Real World
Sharding helps large databases handle more data and users by splitting data across multiple servers.
💼 Career
Understanding sharding is important for database administrators and backend developers managing scalable applications.
Progress0 / 4 steps
1
Create the products collection with sample data
Create a MongoDB collection called products and insert these exact documents: { _id: 1, name: "Laptop", category: "Electronics" }, { _id: 2, name: "Coffee Mug", category: "Kitchen" }, and { _id: 3, name: "Notebook", category: "Stationery" }.
MongoDB
Need a hint?

Use db.products.insertMany() to add multiple documents at once.

2
Define the shard key configuration
Create a variable called shardKey and set it to the object { category: 1 } to use the category field as the shard key.
MongoDB
Need a hint?

Use const shardKey = { category: 1 } to define the shard key object.

3
Enable sharding on the products collection
Use the MongoDB command sh.shardCollection to enable sharding on the products collection in the store database using the shardKey variable.
MongoDB
Need a hint?

Use sh.shardCollection("store.products", shardKey) to enable sharding.

4
Check the sharding status
Add the command sh.status() to display the current sharding status of the MongoDB cluster.
MongoDB
Need a hint?

Use sh.status() to see the sharding details.