MongoDB Exercises

Welcome to TheCodingCollege.com, your trusted resource for coding and programming knowledge. In this guide, we’ve curated practical MongoDB exercises designed to strengthen your understanding of MongoDB concepts and commands. These exercises are perfect for beginners and intermediate developers looking to gain hands-on experience with MongoDB.

Why Practice MongoDB Exercises?

MongoDB is a powerful NoSQL database widely used in modern web development. By solving exercises, you can:

  • Reinforce Key Concepts: Improve understanding of MongoDB commands and operations.
  • Enhance Problem-Solving Skills: Learn to handle real-world scenarios.
  • Boost Confidence: Prepare for coding interviews or practical applications.

Prerequisites

Before starting the exercises, ensure you have:

  • MongoDB installed or access to MongoDB Atlas.
  • A basic understanding of MongoDB commands (CRUD, Aggregation, Indexing, etc.).
  • MongoDB client (e.g., mongosh or any GUI like MongoDB Compass).

MongoDB Exercises

1. Creating a Database

Task: Create a database named thecodingcollege.
Hint: Use the use command to create a database in MongoDB.

use thecodingcollege

2. Creating a Collection

Task: Create a collection named students in the thecodingcollege database.
Hint: Use the db.createCollection() method or insert a document directly to create a collection.

db.createCollection("students")

3. Inserting Documents

Task: Insert the following student documents into the students collection:

  • { name: "Alice", age: 21, course: "Computer Science" }
  • { name: "Bob", age: 23, course: "Information Technology" }

Solution:

db.students.insertMany([
    { name: "Alice", age: 21, course: "Computer Science" },
    { name: "Bob", age: 23, course: "Information Technology" }
])

4. Querying Data

Task: Find all students enrolled in the Computer Science course.
Hint: Use the find() method with a query filter.

db.students.find({ course: "Computer Science" })

5. Updating Documents

Task: Update Bob’s age to 24.
Hint: Use the updateOne() method with the $set operator.

db.students.updateOne(
    { name: "Bob" },
    { $set: { age: 24 } }
)

6. Deleting Documents

Task: Delete the student named Alice from the collection.
Hint: Use the deleteOne() method.

db.students.deleteOne({ name: "Alice" })

7. Aggregation

Task: Count the number of students in each course.
Hint: Use the $group stage in an aggregation pipeline.

db.students.aggregate([
    { $group: { _id: "$course", count: { $sum: 1 } } }
])

8. Indexing

Task: Create an index on the course field to optimize queries.
Hint: Use the createIndex() method.

db.students.createIndex({ course: 1 })

9. Schema Validation

Task: Add schema validation to ensure that every document in the students collection has a name and an age field.
Hint: Use the validator option in the createCollection() method.

db.createCollection("students", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["name", "age"],
            properties: {
                name: { bsonType: "string" },
                age: { bsonType: "int", minimum: 1 }
            }
        }
    }
})

10. Real-World Challenge

Task: You are building a library database. Perform the following:

  1. Create a books collection.
  2. Insert at least three books with fields like title, author, year, and availableCopies.
  3. Find all books published after 2010.
  4. Update the availableCopies of one book.
  5. Delete a book by its title.

Hint: Combine the concepts learned above to complete the challenge.

Best Practices

  1. Backup Your Data: Before performing destructive actions like deletion, back up your data.
  2. Use Proper Indexing: Optimize queries with indexes for large datasets.
  3. Follow Schema Validation: Enforce data integrity with schema validation rules.

Next Steps

Practice these exercises to solidify your MongoDB skills. For more tutorials, exercises, and in-depth guides, visit TheCodingCollege.com.

Leave a Comment