0
0
MongoDBquery~30 mins

Array expressions ($size, $arrayElemAt, $filter) in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Working with Array Expressions in MongoDB: $size, $arrayElemAt, $filter
📖 Scenario: You are managing a small online bookstore database. Each book document contains an array of reviews from readers. You want to analyze these reviews to understand how many reviews each book has, pick a specific review, and filter reviews based on rating.
🎯 Goal: Build a MongoDB aggregation pipeline that uses $size to count reviews, $arrayElemAt to pick a specific review, and $filter to select reviews with a rating above a threshold.
📋 What You'll Learn
Create a collection called books with documents containing a title and an array field reviews.
Add a variable minRating to set the minimum rating for filtering reviews.
Write an aggregation pipeline that adds fields: reviewCount using $size, firstReview using $arrayElemAt, and goodReviews using $filter with minRating.
Complete the pipeline by projecting the new fields along with the book title.
💡 Why This Matters
🌍 Real World
Analyzing customer reviews in an online bookstore to understand feedback quantity and quality.
💼 Career
Using MongoDB aggregation with array expressions is common in data analysis and backend development roles.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a MongoDB collection called books with two documents. Each document must have a title string and a reviews array with exactly these objects: { reviewer: "Alice", rating: 5 }, { reviewer: "Bob", rating: 3 }, and { reviewer: "Charlie", rating: 4 } for the first book, and { reviewer: "Dave", rating: 2 }, { reviewer: "Eve", rating: 5 } for the second book.
MongoDB
Need a hint?

Use db.books.insertMany([...]) with the exact documents as described.

2
Set the minimum rating threshold
Create a variable called minRating and set it to the number 4. This will be used to filter reviews with ratings 4 or higher.
MongoDB
Need a hint?

Use const minRating = 4 to define the threshold.

3
Build the aggregation pipeline with $size, $arrayElemAt, and $filter
Write an aggregation pipeline on books that adds three new fields: reviewCount using $size on reviews, firstReview using $arrayElemAt to get the first review (index 0), and goodReviews using $filter to include only reviews with rating greater than or equal to minRating. Use $addFields stage.
MongoDB
Need a hint?

Use $addFields with $size, $arrayElemAt, and $filter as shown.

4
Project the final fields including the title
Complete the aggregation pipeline by adding a $project stage that includes title, reviewCount, firstReview, and goodReviews fields only.
MongoDB
Need a hint?

Use $project to include only the specified fields with value 1.