0
0
MongoDBquery~30 mins

$project stage for shaping output in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$project stage for shaping output
📖 Scenario: You work at a small bookstore that keeps its inventory in a MongoDB collection. Each book document has details like title, author, price, and stock count.You want to create a report that only shows the book title and price, hiding other details.
🎯 Goal: Build a MongoDB aggregation pipeline using the $project stage to shape the output documents to include only the title and price fields.
📋 What You'll Learn
Create a collection named books with 3 book documents having fields title, author, price, and stock.
Define a variable projection that specifies the $project stage to include only title and price.
Write an aggregation query on books using the projection variable.
Complete the pipeline so the output documents only show title and price.
💡 Why This Matters
🌍 Real World
Shaping output with $project is common when you want to show only relevant data to users or reports, hiding sensitive or unnecessary fields.
💼 Career
Many jobs require working with MongoDB aggregations to optimize data retrieval and presentation, making $project a key skill.
Progress0 / 4 steps
1
Create the books collection with 3 book documents
Create a variable called books and assign it an array with these exact 3 documents:
{ title: "The Hobbit", author: "J.R.R. Tolkien", price: 15, stock: 5 },
{ title: "1984", author: "George Orwell", price: 12, stock: 8 },
{ title: "To Kill a Mockingbird", author: "Harper Lee", price: 10, stock: 3 }
MongoDB
Need a hint?

Use an array of objects with the exact field names and values.

2
Define the projection variable for the $project stage
Create a variable called projection and assign it an object with a $project field that includes only title and price set to 1.
MongoDB
Need a hint?

Use $project with title: 1 and price: 1 to include only those fields.

3
Write the aggregation query using the projection variable
Create a variable called result and assign it the result of calling books.aggregate with an array containing the projection variable.
MongoDB
Need a hint?

Use books.aggregate with an array containing projection.

4
Complete the pipeline to output only title and price
Add a final line to the code that assigns resultArray to the array form of result by calling toArray().
MongoDB
Need a hint?

Call toArray() on result to get the final array.