$lookup with pipeline (advanced join) in MongoDB
📖 Scenario: You are managing a MongoDB database for a bookstore. There are two collections: books and reviews. Each book has an _id and a title. The reviews collection stores customer reviews with fields book_id (referencing books._id), rating (1 to 5), and comment.You want to create a query that joins books with their reviews, but only includes reviews with a rating of 4 or higher. Also, you want to calculate the average rating for each book from these filtered reviews.
🎯 Goal: Build a MongoDB aggregation pipeline using $lookup with a pipeline to join books with filtered reviews (rating ≥ 4), and add a field averageHighRating showing the average of these high ratings.
📋 What You'll Learn
Create a
books collection with exactly 3 books with specified _id and title.Create a
reviews collection with exactly 5 reviews referencing the books, with various ratings.Write an aggregation on
books using $lookup with a pipeline to join only reviews with rating >= 4.Add a field
averageHighRating to each book showing the average rating of the joined reviews.💡 Why This Matters
🌍 Real World
Filtering and joining related data with conditions is common in real-world databases, such as showing only positive reviews for products.
💼 Career
Understanding $lookup with pipeline is important for MongoDB developers to write efficient and powerful queries for complex data relationships.
Progress0 / 4 steps