Lab 2 - Requêtes MongoDB
Queries to design on ecommerce database and products collection
- Find all products with a price greater than $500.
- Find all products from a specific brand (e.g., “TechPro”).
- Count the total number of products in the collection.
- Find all products that have a rating of exactly 5.0.
- Find all products that have received more than 100 reviews.
- Find the top 5 most expensive products.
- Find all products with an average rating greater than 4.0 and a price less than $300.
- Find the average price of all products for each brand.
- Find products that have at least 2 images and have been updated in the last 60 days.
- 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
- Find all products with a price greater than $500.
db.products.find({ "price": { "$gt": 500 } })
- Find all products from a specific brand (e.g., “TechPro”).
db.products.find({ "brand": "TechPro" })
- Count the total number of products in the collection.
db.products.count()
- Find all products that have a rating of exactly 5.0.
db.products.find({ "rating.average": 5.0 })
- Find all products that have received more than 100 reviews.
db.products.find({ "rating.total_reviews": { "$gt": 100 } })
- Find the top 5 most expensive products.
db.products.find().sort({ "price": -1 }).limit(5)
- 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 } }
]
})
- Find the average price of all products for each brand.
db.products.aggregate([
{ "$group": { "_id": "$brand", "averagePrice": { "$avg": "$price" } } }
])
- 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 } } }
]
})
- 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" }
}}
])