0
0
MongoDBquery~30 mins

$addToSet accumulator for unique arrays in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$addToSet accumulator for unique arrays
📖 Scenario: You are managing a database for a book club. Each member can borrow multiple books, and you want to keep track of all unique book titles borrowed by each member.
🎯 Goal: Build an aggregation pipeline that groups the data by member and collects a unique list of all book titles they have borrowed using the $addToSet accumulator.
📋 What You'll Learn
Create a collection named borrowedBooks with documents containing member and bookTitle fields.
Add a configuration variable for the aggregation pipeline stages.
Write an aggregation query that groups by member and uses $addToSet to collect unique bookTitle values.
Complete the aggregation pipeline with a final stage to format the output.
💡 Why This Matters
🌍 Real World
Tracking unique items borrowed or purchased by users is common in libraries, stores, and online platforms.
💼 Career
Understanding $addToSet helps in writing efficient aggregation queries for data analysis and reporting in MongoDB.
Progress0 / 4 steps
1
Create the borrowedBooks collection with sample data
Create a collection called borrowedBooks and insert these exact documents: { member: "Alice", bookTitle: "Moby Dick" }, { member: "Alice", bookTitle: "1984" }, { member: "Bob", bookTitle: "Moby Dick" }, { member: "Alice", bookTitle: "Moby Dick" }, { member: "Bob", bookTitle: "The Hobbit" }.
MongoDB
Need a hint?

Use db.collection.insertMany() to add multiple documents at once.

2
Define the aggregation pipeline variable
Create a variable called pipeline and assign it an array with one object that groups documents by member.
MongoDB
Need a hint?

Use $group with _id: "$member" to group by member.

3
Add $addToSet to collect unique book titles
Modify the $group stage in the pipeline variable to add a field called uniqueBooks that uses $addToSet to collect unique bookTitle values.
MongoDB
Need a hint?

Inside $group, add uniqueBooks: { $addToSet: "$bookTitle" }.

4
Add a $project stage to format the output
Add a $project stage to the pipeline variable that renames _id to member and includes uniqueBooks in the output.
MongoDB
Need a hint?

Use $project to rename _id to member and include uniqueBooks.