0
0
MongoDBquery~30 mins

Shard key selection importance in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Shard Key Selection Importance
📖 Scenario: You are managing a large online store database using MongoDB. To handle the growing number of orders efficiently, you want to distribute the data across multiple servers using sharding. Choosing the right shard key is very important to keep the database fast and balanced.
🎯 Goal: Build a simple MongoDB sharded collection setup by selecting an appropriate shard key and enabling sharding on the database and collection.
📋 What You'll Learn
Create a database called storeDB
Create a collection called orders inside storeDB
Enable sharding on the storeDB database
Shard the orders collection using the orderDate field as the shard key
💡 Why This Matters
🌍 Real World
Large databases need sharding to handle lots of data and traffic efficiently. Choosing the right shard key helps keep the database fast and balanced.
💼 Career
Database administrators and backend engineers often configure sharding to scale applications. Understanding shard keys is essential for managing distributed databases.
Progress0 / 4 steps
1
Create the database and collection
Create a database called storeDB and a collection called orders inside it.
MongoDB
Need a hint?

Use use storeDB to switch to the database, then db.createCollection('orders') to create the collection.

2
Enable sharding on the database
Enable sharding on the storeDB database using the command sh.enableSharding('storeDB').
MongoDB
Need a hint?

Use the sh.enableSharding() command with the database name as a string.

3
Select the shard key
Choose the orderDate field as the shard key for the orders collection by defining the shard key object and creating an index on it. This helps distribute data based on order dates.
MongoDB
Need a hint?

Define a variable shardKey as an object with orderDate set to 1 for ascending order. Then create the index with db.orders.createIndex(shardKey).

4
Shard the collection using the shard key
Shard the orders collection in storeDB using the orderDate field as the shard key with sh.shardCollection('storeDB.orders', shardKey).
MongoDB
Need a hint?

Use sh.shardCollection() with the full collection name and the shard key variable.