Lab 2 - Requêtes MongoDB

Queries to design on ecommerce database and products collection

  1. Find all products with a price greater than $500.
  2. Find all products from a specific brand (e.g., “TechPro”).
  3. Count the total number of products in the collection.
  4. Find all products that have a rating of exactly 5.0.
  5. Find all products that have received more than 100 reviews.
  6. Find the top 5 most expensive products.
  7. Find all products with an average rating greater than 4.0 and a price less than $300.
  8. Find the average price of all products for each brand.
  9. Find products that have at least 2 images and have been updated in the last 60 days.
  10. Calculate the average rating and total number of reviews for products in a specific category (e.g., “Electronics”).

Tip: don’t forget the use this query to get the structure of a product:

db.products.findOne()

Solutions

  1. Find all products with a price greater than $500.
db.products.find({ "price": { "$gt": 500 } })
  1. Find all products from a specific brand (e.g., “TechPro”).
db.products.find({ "brand": "TechPro" })
  1. Count the total number of products in the collection.
db.products.count()
  1. Find all products that have a rating of exactly 5.0.
db.products.find({ "rating.average": 5.0 })
  1. Find all products that have received more than 100 reviews.
db.products.find({ "rating.total_reviews": { "$gt": 100 } })
  1. Find the top 5 most expensive products.
db.products.find().sort({ "price": -1 }).limit(5)
  1. Find all products with an average rating greater than 4.0 and a price less than $300.
db.products.find({
    "$and": [
        { "rating.average": { "$gt": 4.0 } },
        { "price": { "$lt": 300 } }
    ]
})
  1. Find the average price of all products for each brand.
db.products.aggregate([
    { "$group": { "_id": "$brand", "averagePrice": { "$avg": "$price" } } }
])
  1. Find products that are featured, have a stock quantity less than 50, and have received at least one 5-star review.
db.products.find({
    "$and": [
        { "isFeatured": true },
        { "stock": { "$lt": 50 } },
        { "reviews": { "$elemMatch": { "rating": 5 } } }
    ]
})
  1. Calculate the average rating and total number of reviews for products in a specific category (e.g., “Electronics”).
db.products.aggregate([
    { "$match": { "category": "Electronics" } },
    { "$group": {
        "_id": null,
        "averageRating": { "$avg": "$rating.average" },
        "totalReviews": { "$sum": "$rating.total_reviews" }
    }}
])