Bird
Raised Fist0
MongoDBquery~30 mins

Choosing a good shard key in MongoDB - Mini Project: Build & Apply

Choose your learning style10 modes available
Choosing a Good Shard Key in MongoDB
📖 Scenario: You are managing a MongoDB database for an online bookstore. The database stores information about books, including their _id, title, author, genre, and copies_sold. The database is growing fast, and you want to distribute the data across multiple servers to improve performance and scalability.To do this, you need to choose a good shard key for the books collection. A shard key is a field that MongoDB uses to split the data into smaller parts called shards. Choosing the right shard key helps the database find and store data efficiently.
🎯 Goal: In this project, you will create a books collection with sample data, define a shard key, and apply sharding to the collection. You will learn how to pick a shard key that balances the data well and supports common queries.
📋 What You'll Learn
Create a books collection with 5 sample documents with exact fields and values
Define a shard key variable called shardKey with the field name to shard on
Enable sharding on the database and shard the books collection using the shardKey
Use the sh.shardCollection() command with the correct shard key format
💡 Why This Matters
🌍 Real World
Sharding helps large databases handle more data and users by splitting data across servers. Choosing a good shard key is important to keep data balanced and queries fast.
💼 Career
Database administrators and backend engineers often configure sharding to scale applications. Understanding shard keys is key to managing big data systems effectively.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a books collection with these exact 5 documents: { _id: 1, title: "The Great Gatsby", author: "F. Scott Fitzgerald", genre: "Classic", copies_sold: 25000000 }, { _id: 2, title: "1984", author: "George Orwell", genre: "Dystopian", copies_sold: 30000000 }, { _id: 3, title: "To Kill a Mockingbird", author: "Harper Lee", genre: "Classic", copies_sold: 40000000 }, { _id: 4, title: "The Hobbit", author: "J.R.R. Tolkien", genre: "Fantasy", copies_sold: 100000000 }, { _id: 5, title: "Harry Potter and the Sorcerer's Stone", author: "J.K. Rowling", genre: "Fantasy", copies_sold: 120000000 }.
MongoDB
Hint

Use db.books.insertMany() with an array of objects matching the exact fields and values.

2
Define the shard key field
Create a variable called shardKey and set it to the string "genre" to use the genre field as the shard key.
MongoDB
Hint

Use const shardKey = "genre" to define the shard key field.

3
Enable sharding on the database
Run the command sh.enableSharding("bookstore") to enable sharding on the bookstore database.
MongoDB
Hint

Use sh.enableSharding("bookstore") to turn on sharding for the database.

4
Shard the books collection using the shard key
Run the command sh.shardCollection("bookstore.books", { [shardKey]: 1 }) to shard the books collection on the genre field in ascending order.
MongoDB
Hint

Use sh.shardCollection("bookstore.books", { [shardKey]: 1 }) to shard the collection on the genre field.

Practice

(1/5)
1. Which of the following is the most important characteristic of a good shard key in MongoDB?
easy
A. It is the smallest field in the document.
B. It is always a string type.
C. It has many unique values to distribute data evenly.
D. It contains only numeric values.

Solution

  1. Step 1: Understand shard key purpose

    A shard key is used to split data across servers to balance load and improve speed.
  2. Step 2: Identify key characteristic for even distribution

    A good shard key has many unique values to avoid data being stored unevenly on shards.
  3. Final Answer:

    It has many unique values to distribute data evenly. -> Option C
  4. Quick Check:

    Unique values = balanced shards [OK]
Hint: Choose shard keys with many unique values for balance [OK]
Common Mistakes:
  • Thinking shard key must be string
  • Choosing small fields regardless of uniqueness
  • Assuming numeric only keys are best
2. Which of the following is the correct syntax to create a sharded collection with shard key { userId: 1 } in MongoDB?
easy
A. sh.shardCollection('mydb.users', 'userId')
B. db.shardCollection('users', { userId: 1 })
C. sh.shardCollection('users', { userId: 1 })
D. sh.shardCollection('mydb.users', { userId: 1 })

Solution

  1. Step 1: Recall syntax for sharding a collection

    The correct command is sh.shardCollection(namespace, shardKey), where namespace is 'database.collection'.
  2. Step 2: Match options to syntax

    sh.shardCollection('mydb.users', { userId: 1 }) uses full namespace 'mydb.users' and correct shard key object { userId: 1 }.
  3. Final Answer:

    sh.shardCollection('mydb.users', { userId: 1 }) -> Option D
  4. Quick Check:

    Full namespace + shard key object = correct syntax [OK]
Hint: Use full 'db.collection' name and shard key object [OK]
Common Mistakes:
  • Using db.shardCollection instead of sh.shardCollection
  • Passing shard key as string instead of object
  • Omitting database name in namespace
3. Given a collection sharded on { country: 1 }, which query will benefit most from the shard key?
medium
A. db.users.find({ age: { $gt: 30 } })
B. db.users.find({ country: 'USA' })
C. db.users.find({ name: 'Alice' })
D. db.users.find({ city: 'New York' })

Solution

  1. Step 1: Understand shard key usage in queries

    Queries that include the shard key field can target specific shards, improving speed.
  2. Step 2: Identify query with shard key field

    Only db.users.find({ country: 'USA' }) filters by country, the shard key, so it benefits most.
  3. Final Answer:

    db.users.find({ country: 'USA' }) -> Option B
  4. Quick Check:

    Query includes shard key field = faster query [OK]
Hint: Queries with shard key filter run faster [OK]
Common Mistakes:
  • Assuming any query runs faster on sharded collection
  • Ignoring shard key field in query
  • Confusing shard key with indexed fields
4. You created a shard key on { userId: 1 } but notice all data is stored on one shard. What is the likely cause?
medium
A. The userId field has low cardinality (few unique values).
B. The shard key was created with descending order { userId: -1 }.
C. The collection is not sharded yet.
D. The shard key field is missing in some documents.

Solution

  1. Step 1: Understand shard key distribution

    If the shard key has few unique values, data will cluster on few shards causing imbalance.
  2. Step 2: Analyze options

    Low cardinality of userId causes data to be stored on one shard, matching the problem.
  3. Final Answer:

    The userId field has low cardinality (few unique values). -> Option A
  4. Quick Check:

    Low uniqueness = data imbalance [OK]
Hint: Low unique shard key values cause data to cluster [OK]
Common Mistakes:
  • Thinking shard key order affects distribution
  • Assuming collection is not sharded without checking
  • Ignoring missing shard key fields in documents
5. You have a large collection of orders with fields orderId, customerId, and orderDate. You want to shard to optimize queries filtering by customerId and range queries on orderDate. Which shard key is best?
hard
A. { customerId: 1, orderDate: 1 }
B. { orderDate: 1 }
C. { orderId: 1 }
D. { customerId: 1 }

Solution

  1. Step 1: Identify query patterns

    Queries filter by customerId and also use range on orderDate.
  2. Step 2: Choose shard key matching query patterns

    A compound shard key with { customerId: 1, orderDate: 1 } supports both equality and range queries efficiently.
  3. Final Answer:

    { customerId: 1, orderDate: 1 } -> Option A
  4. Quick Check:

    Compound shard key matches query filters [OK]
Hint: Use compound shard key for multiple query filters [OK]
Common Mistakes:
  • Choosing single field shard key ignoring query patterns
  • Using orderId which is not queried
  • Not using compound keys for combined filters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard