Showing posts with label Database Practice. Show all posts
Showing posts with label Database Practice. Show all posts

MongoDB Practice Questions with Solutions (Beginner to Advanced Exercises)

๐Ÿงช MongoDB Practice Questions with Solutions (Beginner to Advanced)


Learning MongoDB is not just about reading concepts—it’s about practicing real problems.

Here, you’ll solve hands-on MongoDB exercises step by step. Each question includes:

  • ✅ Problem
  • ✅ Solution
  • ✅ Explanation

By the end, you’ll feel confident working with real-world MongoDB scenarios.


๐ŸŸข Level 1: Beginner Exercises

✅ Q1: Create a Database and Collection

Problem:
Create a database called school and a collection called students.

Solution:

use school
db.createCollection("students")

Explanation:
use school creates (or switches to) the database and createCollection() creates a new collection.

---

✅ Q2: Insert Documents

Problem:
Insert 3 student records with fields: name, age, course.

Solution:

db.students.insertMany([
  { name: "Amit", age: 20, course: "BCA" },
  { name: "Sara", age: 22, course: "MCA" },
  { name: "John", age: 19, course: "BSc" }
])

Explanation:
insertMany() allows inserting multiple documents at once.

---

✅ Q3: Find All Documents

Problem:
Retrieve all students from the collection.

Solution:

db.students.find()

Explanation:
find() returns all documents in the collection.

---

✅ Q4: Filter Data

Problem:
Find students with age greater than 20.

Solution:

db.students.find({ age: { $gt: 20 } })

Explanation:
$gt means "greater than".



๐ŸŸก Level 2: Intermediate Exercises

✅ Q5: Update a Document

Problem:
Update "Amit"’s course to "B.Tech".

Solution:

db.students.updateOne(
  { name: "Amit" },
  { $set: { course: "B.Tech" } }
)

Explanation:
$set updates specific fields.

---

✅ Q6: Delete a Document

Problem:
Delete the student named "John".

Solution:

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

Explanation:
deleteOne() removes one matching document.

---

✅ Q7: Sort Data

Problem:
Sort students by age in descending order.

Solution:

db.students.find().sort({ age: -1 })

Explanation:
-1 = descending, 1 = ascending.

---

✅ Q8: Limit Results

Problem:
Show only 2 students.

Solution:

db.students.find().limit(2)

Explanation:
limit() restricts number of results.



๐Ÿ”ต Level 3: Advanced Exercises

✅ Q9: Design a Schema (Embedding vs Referencing)

Problem:
Design a schema for Users and Orders where each user can have many orders.

Solution:

// Users Collection
{
  _id: 1,
  name: "Amit"
}

// Orders Collection
{
  _id: 101,
  user_id: 1,
  product: "Laptop",
  price: 50000
}

Explanation:
Use referencing when data grows large. Avoid embedding too many orders inside a single document.

---

✅ Q10: Aggregation Query

Problem:
Find the average age of students.

Solution:

db.students.aggregate([
  {
    $group: {
      _id: null,
      averageAge: { $avg: "$age" }
    }
  }
])

Explanation:
$group is used for aggregation and $avg calculates average.

---

✅ Q11: Find Duplicate Data

Problem:
Find duplicate student names.

Solution:

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

Explanation:
Groups data by name and filters duplicates using $match.


๐Ÿš€ Bonus Challenge

Challenge:
Design a database for a blog system with Users, Posts, and Comments.

  • Which data will you embed?
  • Which data will you reference?
  • Why?

๐ŸŽฏ Final Thoughts

If you completed these exercises, you now understand:

The best way to learn MongoDB is:
Practice → Build → Break → Fix → Repeat


๐Ÿ“š What to Learn Next


๐Ÿ’ฌ Your Turn:
Which question did you find most challenging? Let us know in the comments!


CRUD Operations in SQL vs MongoDB – Practice Task + Assignment for Beginners


๐Ÿงช Practice Task – CRUD Basics in SQL & MongoDB


Here's a Practice Task + Mini Assignment that complements Part 6: CRUD Operations in SQL vs NoSQL. It's designed to reinforce the differences in syntax and logic between SQL and MongoDB, while staying simple and highly practical for beginners.


๐ŸŽฏ Objective:

Perform basic Create, Read, Update, and Delete operations in both SQL and NoSQL (MongoDB).


๐Ÿ”น Scenario: School Students Data

You are managing a student database and need to do the following:

  1. Add a new student

  2. Fetch the student's data

  3. Update the student’s class

  4. Delete the student’s record


๐Ÿ“Œ A. SQL Practice

1. Create

INSERT INTO Students (StudentID, Name, Class)
VALUES (2, 'Ravi Kumar', '10B');

2. Read

SELECT * FROM Students WHERE StudentID = 2;

3. Update

UPDATE Students SET Class = '10C' WHERE StudentID = 2;

4. Delete

DELETE FROM Students WHERE StudentID = 2;


๐Ÿ“Œ B. MongoDB Practice

1. Create

db.students.insertOne({
  student_id: 2,
  name: "Ravi Kumar",
  class: "10B",
  marks: [{ subject: "English", score: 82 }]
});

2. Read

db.students.findOne({ student_id: 2 });

3. Update

db.students.updateOne(
  { student_id: 2 },
  { $set: { class: "10C" } }
);

4. Delete

db.students.deleteOne({ student_id: 2 });

๐Ÿ“ Mini Assignment: Build Your Own CRUD Set


๐Ÿ”น Instructions:

  1. Choose a student name and add them to both SQL and NoSQL.

  2. Add a subject and score for them (embedded in NoSQL).

  3. Read and display their data.

  4. Change their class and update their English score to 90.

  5. Finally, delete the record in both systems.


๐Ÿ’ก Challenge (Optional):

  • In SQL, insert marks into a separate Marks table and join it to fetch the student’s full profile.

  • In MongoDB, use $push to add a new subject to the marks array.


✅ Bonus: MongoDB $push Example

db.students.updateOne(
  { student_id: 2 },
  { $push: { marks: { subject: "Science", score: 88 } } }
);

Do you Know: The $push operator is used to add a new element to an array field in MongoDB.



Tell Us in Comments:

Which syntax do you find easier — SQL or MongoDB? Share your thoughts in the comments!

Also, Try the assignment above and share your solution in the comments.



To know about CRUD opreations read  Part 6: CRUD Operations in SQL vs NoSQL – A Beginner's Guide


✅ What’s Next?

Next: solution for the mini assignment in both SQL and NoSQL



Featured Post

MongoDB Full Real-World Project Practice (Complete Challenge)

๐Ÿงฉ MongoDB Practice Series – Full Real-World Project Challenge (Part 8) ← Go to Previous Welcome to Part 8 of the MongoDB Practice Se...

Popular Posts