Section 12: Practice

πŸ“‹ Practice Assignments

Real-World MongoDB Projects - Restaurant, Books & Movies

1000x
Faster Queries
15+
Techniques
20
Interview Q&A

πŸŽ“ About These Assignments

These comprehensive assignments will help you master MongoDB through real-world scenarios. Each project covers the full spectrum of MongoDB operations from basic CRUD to advanced aggregations.

πŸ“˜ Learning Objectives:
  • CRUD Mastery: Create, read, update, and delete operations
  • Query Optimization: Write efficient queries with proper indexing
  • Aggregation Pipeline: Complex data analysis and transformations
  • Schema Design: Design effective document structures
  • Real-World Scenarios: Solve practical business problems

Your Progress

3
Total Projects
60+
Total Tasks
~20h
Estimated Time
πŸ’‘ How to Approach:
  • Start with the data schema - understand the structure
  • Set up sample data first before writing queries
  • Test each query thoroughly with different scenarios
  • Optimize queries using explain() and proper indexing
  • Document your approach and any challenges faced
πŸ•

Restaurant Management System Beginner Intermediate

Build a complete restaurant ordering and management system with menu items, orders, customers, and reviews.

Database Schema

Create the following collections:

Collection: restaurants
{
  _id: ObjectId,
  name: String,
  cuisine: String,
  address: {
    street: String,
    city: String,
    zipcode: String,
    coordinates: [longitude, latitude]
  },
  rating: Number,
  priceRange: String, // "$", "$$", "$$$", "$$$$"
  openingHours: {
    monday: { open: String, close: String },
    tuesday: { open: String, close: String },
    // ... other days
  },
  features: [String], // ["wifi", "parking", "outdoor seating"]
  contactPhone: String,
  establishedYear: Number
}
Collection: menu_items
{
  _id: ObjectId,
  restaurantId: ObjectId,
  name: String,
  category: String, // "appetizer", "main course", "dessert", "beverage"
  description: String,
  price: Number,
  ingredients: [String],
  allergens: [String],
  isVegetarian: Boolean,
  isVegan: Boolean,
  isGlutenFree: Boolean,
  spicyLevel: Number, // 0-5
  calories: Number,
  preparationTime: Number, // minutes
  isAvailable: Boolean,
  imageUrl: String
}
Collection: customers
{
  _id: ObjectId,
  name: String,
  email: String,
  phone: String,
  address: {
    street: String,
    city: String,
    zipcode: String,
    coordinates: [longitude, latitude]
  },
  joinedDate: Date,
  loyaltyPoints: Number,
  preferences: {
    favoriteRestaurants: [ObjectId],
    dietaryRestrictions: [String],
    spicePreference: Number
  }
}
Collection: orders
{
  _id: ObjectId,
  customerId: ObjectId,
  restaurantId: ObjectId,
  orderDate: Date,
  items: [
    {
      menuItemId: ObjectId,
      name: String,
      quantity: Number,
      price: Number,
      specialInstructions: String
    }
  ],
  totalAmount: Number,
  deliveryAddress: {
    street: String,
    city: String,
    zipcode: String
  },
  orderType: String, // "delivery", "pickup", "dine-in"
  status: String, // "pending", "preparing", "ready", "delivered", "cancelled"
  paymentMethod: String,
  deliveryTime: Date,
  tips: Number,
  discount: Number
}
Collection: reviews
{
  _id: ObjectId,
  restaurantId: ObjectId,
  customerId: ObjectId,
  orderId: ObjectId,
  rating: Number, // 1-5
  foodRating: Number,
  serviceRating: Number,
  ambianceRating: Number,
  comment: String,
  reviewDate: Date,
  photos: [String],
  helpful: Number, // count of helpful votes
  response: {
    text: String,
    date: Date
  }
}

Part 1: Setup & Basic CRUD (10 tasks)

  • Create the database "restaurant_db" and all five collections mentioned above
  • Insert at least 5 restaurants with different cuisines (Italian, Chinese, Mexican, Indian, American)
  • Insert at least 20 menu items across different restaurants with varying categories
  • Create 10 customer documents with different preferences
  • Insert 15 orders with different statuses and order types
  • Add 20 reviews with ratings between 1-5 stars
  • Find all Italian restaurants in the database
  • Find all vegetarian menu items under $15
  • Find customers who joined after January 1, 2024
  • Update a restaurant's rating based on new reviews

Part 2: Advanced Queries (10 tasks)

  • Find all restaurants within 5 miles of coordinates [-73.856077, 40.848447] (use $geoWithin or mock with math)
  • Find all menu items that are both vegan AND gluten-free
  • Get all orders placed in the last 30 days with total amount > $50
  • Find restaurants that have "wifi" AND "parking" in their features
  • Find customers who have ordered from more than 3 different restaurants
  • Get all menu items with spicy level >= 3 and calories < 500
  • Find orders with status "delivered" and tips >= 10% of totalAmount
  • Get reviews where overall rating is 5 but food rating is less than 4
  • Find restaurants open on Monday between 6 PM - 9 PM
  • Get all customers who have dietary restrictions of "gluten-free" or "vegan"

Part 3: Aggregation Pipeline (10 tasks)

  • Calculate the average rating for each restaurant
  • Find the top 5 most ordered menu items (by quantity sold)
  • Calculate total revenue for each restaurant from all orders
  • Get the average order value by order type (delivery, pickup, dine-in)
  • Find customers with the highest loyalty points (top 10)
  • Calculate the total number of orders by cuisine type
  • Get monthly revenue trend (group by year-month and sum totalAmount)
  • Find the most popular menu category by number of orders
  • Calculate average preparation time by restaurant
  • Get restaurants with average rating > 4.0 and at least 10 reviews

Part 4: Updates & Complex Operations (5 tasks)

  • Add a new "featured" field to restaurants and set it to true for those with rating > 4.5
  • Update customer loyalty points: add 10 points for each order > $50
  • Mark menu items as unavailable if they contain allergen "peanuts"
  • Update all orders from last year: change status to "archived"
  • Add a "lastOrderDate" field to customers based on their most recent order

Part 5: Advanced Features (5 tasks)

  • Create indexes: compound index on (restaurantId, orderDate) for orders collection
  • Create text index on menu_items (name, description) and search for "spicy chicken"
  • Use $lookup to join orders with customer information and display customer name with each order
  • Create a view "popular_restaurants" showing restaurants with avg rating > 4.0
  • Use $facet to get multiple analytics in one query: total orders, avg order value, and top 3 cuisines

πŸ“ Deliverables:

  • Complete MongoDB script file (.js or .txt) with all queries
  • Sample data insertion scripts
  • Screenshots of query results
  • Brief explanation of your indexing strategy
πŸ“š

Bookstore Management System Beginner Intermediate Advanced

Build an online bookstore with inventory management, sales tracking, author information, and customer reviews.

Database Schema

Collection: books
{
  _id: ObjectId,
  title: String,
  isbn: String,
  authors: [
    {
      authorId: ObjectId,
      name: String,
      role: String // "author", "co-author", "editor"
    }
  ],
  publisher: String,
  publishedDate: Date,
  genres: [String], // ["fiction", "mystery", "thriller"]
  language: String,
  pageCount: Number,
  format: String, // "hardcover", "paperback", "ebook", "audiobook"
  price: {
    retail: Number,
    discount: Number,
    final: Number
  },
  inventory: {
    quantity: Number,
    warehouse: String,
    lastRestocked: Date
  },
  description: String,
  coverImageUrl: String,
  rating: {
    average: Number,
    count: Number
  },
  awards: [String],
  series: {
    name: String,
    position: Number
  }
}
Collection: authors
{
  _id: ObjectId,
  name: String,
  biography: String,
  birthDate: Date,
  nationality: String,
  genres: [String],
  website: String,
  socialMedia: {
    twitter: String,
    instagram: String
  },
  awards: [String],
  booksPublished: Number,
  photoUrl: String
}
Collection: customers
{
  _id: ObjectId,
  name: String,
  email: String,
  username: String,
  joinDate: Date,
  membershipLevel: String, // "bronze", "silver", "gold", "platinum"
  readingPreferences: {
    favoriteGenres: [String],
    favoriteAuthors: [ObjectId]
  },
  purchaseHistory: [ObjectId], // array of order IDs
  wishlist: [ObjectId], // array of book IDs
  readingList: [
    {
      bookId: ObjectId,
      status: String, // "reading", "completed", "want-to-read"
      startDate: Date,
      completedDate: Date
    }
  ]
}
Collection: orders
{
  _id: ObjectId,
  customerId: ObjectId,
  orderNumber: String,
  orderDate: Date,
  items: [
    {
      bookId: ObjectId,
      title: String,
      quantity: Number,
      price: Number
    }
  ],
  subtotal: Number,
  tax: Number,
  shipping: Number,
  total: Number,
  shippingAddress: {
    street: String,
    city: String,
    state: String,
    zipcode: String,
    country: String
  },
  status: String, // "pending", "processing", "shipped", "delivered", "cancelled"
  paymentMethod: String,
  trackingNumber: String,
  deliveredDate: Date
}
Collection: reviews
{
  _id: ObjectId,
  bookId: ObjectId,
  customerId: ObjectId,
  rating: Number, // 1-5 stars
  title: String,
  reviewText: String,
  reviewDate: Date,
  verified: Boolean, // verified purchase
  helpful: {
    yes: Number,
    no: Number
  },
  tags: [String], // ["page-turner", "well-written", "boring"]
  recommended: Boolean
}

Part 1: Setup & Basic Operations (10 tasks)

  • Create database "bookstore_db" with all five collections
  • Insert 20 books across multiple genres (fiction, non-fiction, mystery, sci-fi, romance)
  • Insert 10 author documents with biographical information
  • Create 15 customer accounts with different membership levels
  • Insert 25 orders with various statuses
  • Add 30 book reviews with ratings from 1-5
  • Find all books in the "mystery" genre
  • Get all books by a specific author (by authorId)
  • Find books with price.final less than $20
  • Update inventory quantity for a specific book

Part 2: Complex Queries (10 tasks)

  • Find all books published in the last 5 years with rating > 4.0
  • Get books that are in stock (inventory.quantity > 0) and available in "ebook" format
  • Find customers who are "gold" or "platinum" members
  • Get all orders with total > $100 placed in the last 60 days
  • Find books that are part of a series
  • Get all reviews marked as verified purchases with rating >= 4
  • Find books with more than 3 authors (co-authored books)
  • Get customers who have "mystery" or "thriller" in their favorite genres
  • Find books with inventory quantity < 10 (low stock alert)
  • Get all books in English language with pageCount between 200-400

Part 3: Aggregation Pipeline (12 tasks)

  • Calculate total revenue from all orders (sum of order totals)
  • Find the top 10 best-selling books (by quantity sold)
  • Get average rating for each book (from reviews collection)
  • Calculate total books sold by genre
  • Find the most prolific authors (authors with most books)
  • Get monthly sales revenue (group by year-month)
  • Calculate average order value by membership level
  • Find books with the most reviews
  • Get average book price by format (hardcover, paperback, ebook)
  • Find customers who have completed the most books in their reading list
  • Calculate the percentage of verified vs non-verified reviews
  • Get the top 5 publishers by number of books published

Part 4: Advanced Operations (8 tasks)

  • Use $lookup to join books with their reviews and show avg rating
  • Create compound index on books (genres, price.final) for optimized searching
  • Implement text search: create text index on (title, description) and search for "mystery detective"
  • Use $graphLookup to find all books in a series (if series data is linked)
  • Create a materialized view for "trending_books" (high ratings + recent sales)
  • Use $bucket to categorize books by price ranges ($0-$15, $15-$30, $30-$50, $50+)
  • Update customer membershipLevel based on total purchase amount (Bronze<$100, Silver<$500, Gold<$1000, Platinum$1000+)
  • Use transactions: Place order (decrease inventory, create order, update customer history) - simulate with multiple operations

πŸ“ Deliverables:

  • Complete MongoDB scripts with all queries and operations
  • Data insertion scripts with realistic sample data
  • Index creation statements with explanations
  • Documentation of aggregation pipelines
  • Performance analysis (use explain()) for key queries
🎬

Movie Database & Streaming Platform Intermediate Advanced

Build a comprehensive movie database similar to IMDb with movies, actors, directors, ratings, and user watchlists.

Database Schema

Collection: movies
{
  _id: ObjectId,
  title: String,
  originalTitle: String,
  releaseDate: Date,
  runtime: Number, // minutes
  genres: [String],
  languages: [String],
  countries: [String],
  director: {
    personId: ObjectId,
    name: String
  },
  cast: [
    {
      personId: ObjectId,
      name: String,
      character: String,
      order: Number // billing order
    }
  ],
  plot: String,
  tagline: String,
  budget: Number,
  revenue: Number,
  rating: {
    average: Number,
    count: Number,
    distribution: {
      "5": Number,
      "4": Number,
      "3": Number,
      "2": Number,
      "1": Number
    }
  },
  awards: [
    {
      name: String,
      category: String,
      year: Number,
      won: Boolean
    }
  ],
  studio: String,
  posterUrl: String,
  trailerUrl: String,
  ageRating: String, // "G", "PG", "PG-13", "R", "NC-17"
  status: String, // "released", "post-production", "upcoming"
  streamingPlatforms: [String],
  boxOffice: {
    openingWeekend: Number,
    domestic: Number,
    international: Number
  }
}
Collection: people
{
  _id: ObjectId,
  name: String,
  birthDate: Date,
  birthPlace: String,
  biography: String,
  roles: [String], // ["actor", "director", "producer", "writer"]
  knownFor: [ObjectId], // movie IDs
  awards: [
    {
      name: String,
      year: Number,
      category: String
    }
  ],
  photoUrl: String,
  socialMedia: {
    twitter: String,
    instagram: String
  }
}
Collection: users
{
  _id: ObjectId,
  username: String,
  email: String,
  joinDate: Date,
  profile: {
    displayName: String,
    avatarUrl: String,
    bio: String
  },
  subscriptionPlan: String, // "free", "basic", "premium"
  watchlist: [ObjectId], // movie IDs
  favorites: [ObjectId],
  watchHistory: [
    {
      movieId: ObjectId,
      watchedDate: Date,
      progress: Number, // percentage watched
      completed: Boolean
    }
  ],
  preferences: {
    favoriteGenres: [String],
    languages: [String]
  },
  following: [ObjectId] // user IDs
}
Collection: ratings
{
  _id: ObjectId,
  movieId: ObjectId,
  userId: ObjectId,
  rating: Number, // 1-5 stars or 1-10 scale
  reviewTitle: String,
  reviewText: String,
  ratingDate: Date,
  likes: Number,
  spoiler: Boolean,
  recommended: Boolean,
  watchedDate: Date
}
Collection: streaming_logs
{
  _id: ObjectId,
  userId: ObjectId,
  movieId: ObjectId,
  sessionId: String,
  startTime: Date,
  endTime: Date,
  duration: Number, // seconds watched
  quality: String, // "480p", "720p", "1080p", "4K"
  device: String,
  platform: String,
  completed: Boolean
}

Part 1: Setup & Foundation (8 tasks)

  • Create database "movie_db" with all five collections
  • Insert 25 movies spanning different genres and decades
  • Insert 30 people (actors, directors) with biographical info
  • Create 20 user accounts with different subscription plans
  • Add 40 ratings/reviews across different movies
  • Insert 50 streaming log entries
  • Find all movies released after 2020
  • Get all action movies with rating > 4.0

Part 2: Advanced Query Challenges (12 tasks)

  • Find all movies where a specific actor appears (search by personId in cast)
  • Get movies with runtime between 90-150 minutes and rating > 4.5
  • Find movies that won at least one award
  • Get all users who have "thriller" or "horror" in their favorite genres
  • Find movies available on Netflix OR Amazon Prime (streamingPlatforms)
  • Get movies with revenue > 500 million and budget < 150 million (profitable movies)
  • Find users with "premium" subscription who have watched > 50 movies
  • Get all movies released in the last 2 years with ageRating "PG" or "PG-13"
  • Find people who have "actor" AND "director" in their roles array
  • Get movies where cast includes more than 10 actors
  • Find users who have the same favorite genres as a given user (recommend friends)
  • Get streaming logs where users watched in "4K" quality and completed the movie

Part 3: Complex Aggregation Pipelines (15 tasks)

  • Calculate total box office revenue (domestic + international) for all movies
  • Find the top 10 highest-rated movies (by average rating)
  • Get the most popular genres (by number of movies)
  • Calculate average runtime by genre
  • Find actors who have appeared in the most movies
  • Get total watch time (hours) per user from streaming logs
  • Calculate revenue-to-budget ratio for each movie and find most profitable
  • Find directors with the highest average movie rating
  • Get monthly revenue trend (sum of box office by release month)
  • Calculate the average rating for movies by decade (1980s, 1990s, 2000s, 2010s, 2020s)
  • Find users who have completed the most movies (from watchHistory)
  • Get the distribution of ratings (how many 5-star, 4-star, etc.) for a specific movie
  • Calculate which streaming platform has the most movies
  • Find movies with the best opening weekend relative to budget
  • Get average movie rating by ageRating category

Part 4: Advanced Features & Optimization (10 tasks)

  • Use $lookup to join movies with their director information from people collection
  • Create compound index on movies (genres, releaseDate, rating.average)
  • Implement text search: create text index on (title, plot) and search for "space adventure"
  • Use $facet to get multiple analytics: total movies by genre, avg rating, and top 5 actors
  • Create recommendation system: find movies similar to user's favorites (matching genres)
  • Use $graphLookup to find all movies connected through common cast members
  • Implement "People who watched this also watched" feature using aggregation
  • Create a view "trending_movies" for movies with high recent ratings and watch counts
  • Use $bucket to categorize movies by budget ranges (Indie, Mid-budget, Blockbuster)
  • Performance optimization: use explain() to analyze and optimize the slowest queries

πŸ“ Deliverables:

  • Complete MongoDB script with all queries
  • Sample dataset (at least 25 movies, 30 people, 20 users)
  • Index strategy document explaining your indexing decisions
  • Aggregation pipeline documentation with explanations
  • Performance report with explain() results for key queries
  • Recommendation algorithm explanation

πŸ“€ Submission Guidelines

⚠️ Important Notes:
  • Complete all tasks for each project you choose
  • Test your queries thoroughly with various scenarios
  • Include comments in your code explaining complex queries
  • Document any assumptions you made
  • Optimize queries using proper indexing
πŸ“ File Structure

Organize your submission with separate files for each section (setup, queries, aggregations, etc.)

πŸ’¬ Comments

Add clear comments explaining what each query does and why you chose certain approaches

πŸ“Š Sample Data

Include realistic sample data that demonstrates all features of your schema

⚑ Performance

Use explain() to analyze query performance and document your findings

πŸ” Testing

Test edge cases and document any issues or limitations you encountered

πŸ“ Documentation

Include a README explaining your approach and any design decisions

πŸ“‹ What to Submit:
  • MongoDB Scripts: All queries in .js or .txt format
  • Sample Data: JSON files or insert scripts
  • Screenshots: Results of key queries
  • Documentation: README with explanations
  • Performance Report: explain() results for complex queries

πŸŽ‰ Congratulations!

By completing these assignments, you'll have hands-on experience with:

  • Schema design for real-world applications
  • Complex query writing and optimization
  • Advanced aggregation pipelines
  • Indexing strategies
  • Performance tuning
  • Full-stack MongoDB application concepts

These projects will make excellent portfolio pieces for job applications!