0
0
MongoDBquery~30 mins

$unwind for flattening arrays in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$unwind for flattening arrays in MongoDB
📖 Scenario: You work at an online bookstore. Each book document has a title and an array of authors. You want to list each author separately along with the book title.
🎯 Goal: Build a MongoDB aggregation pipeline that uses $unwind to flatten the authors array so each author appears in its own document with the book title.
📋 What You'll Learn
Create a collection called books with documents containing title and authors array
Add a variable for the aggregation pipeline
Use $unwind on the authors field in the pipeline
Complete the aggregation query to return each author with the book title
💡 Why This Matters
🌍 Real World
Flattening arrays in documents is common when you want to analyze or display each item separately, such as listing each author of a book individually.
💼 Career
Database developers and data analysts often use $unwind in MongoDB to prepare data for reporting, filtering, or transforming nested array data.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a variable called books and assign it an array with these exact documents: { title: 'Learn MongoDB', authors: ['Alice', 'Bob'] } and { title: 'Advanced MongoDB', authors: ['Carol'] }.
MongoDB
Need a hint?

Use an array of objects with title and authors keys exactly as shown.

2
Create the aggregation pipeline variable
Create a variable called pipeline and assign it an empty array [] to start building the aggregation pipeline.
MongoDB
Need a hint?

Start with an empty array for the pipeline.

3
Add the $unwind stage to the pipeline
Add an object with { $unwind: '$authors' } to the pipeline array to flatten the authors array.
MongoDB
Need a hint?

Use { $unwind: '$authors' } inside the pipeline array.

4
Complete the aggregation query using the pipeline
Create a variable called result and assign it the aggregation of books using pipeline with db.collection.aggregate(pipeline) syntax. Assume db.collection is the collection holding books.
MongoDB
Need a hint?

Use const result = db.books.aggregate(pipeline); to run the aggregation.