0
0
MongoDBquery~30 mins

Querying array elements directly in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Querying Array Elements Directly in MongoDB
📖 Scenario: You work at a bookstore that stores book information in a MongoDB collection. Each book document has a title and an array of reviews. Each review has a reviewer's name and a rating.You want to find books that have at least one review with a rating of 5.
🎯 Goal: Build a MongoDB query that finds books with at least one review having a rating of 5 by querying array elements directly.
📋 What You'll Learn
Create a collection named books with documents containing title and reviews array
Add a configuration variable targetRating set to 5
Write a query that finds books where any review's rating equals targetRating
Complete the query to return only the title and matching reviews elements
💡 Why This Matters
🌍 Real World
Many applications store lists of related data inside documents. Querying array elements directly helps find specific items quickly.
💼 Career
Database developers and backend engineers often write queries to filter nested array data in MongoDB for efficient data retrieval.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a MongoDB collection called books and insert these exact documents: { title: "Book A", reviews: [{ reviewer: "Alice", rating: 4 }, { reviewer: "Bob", rating: 5 }] } and { title: "Book B", reviews: [{ reviewer: "Carol", rating: 3 }, { reviewer: "Dave", rating: 2 }] }.
MongoDB
Need a hint?

Use db.books.insertMany() with an array of two objects as shown.

2
Set the targetRating variable
Create a variable called targetRating and set it to the number 5.
MongoDB
Need a hint?

Use const targetRating = 5 to create the variable.

3
Write the query to find books with a review rating equal to targetRating
Write a MongoDB query using db.books.find() that finds documents where the reviews array has at least one element with rating equal to targetRating. Use the query { "reviews.rating": targetRating }.
MongoDB
Need a hint?

Use dot notation "reviews.rating" in the query object.

4
Complete the query to return only title and matching reviews elements
Complete the query by calling db.books.find() with the query and a projection that returns only title and the matching reviews.$ element.
MongoDB
Need a hint?

Use { title: 1, "reviews.$": 1 } as the projection to get only the title and the matched review.