0
0
MongoDBquery~30 mins

$out and $merge for writing results in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$out and $merge for writing results in MongoDB
📖 Scenario: You work at a small online bookstore. You have a collection called sales that records each book sale with fields like title, author, and copies_sold. You want to create a summary collection that shows total copies sold per author.
🎯 Goal: Build an aggregation pipeline that groups sales by author and sums the copies sold. Then, write the results into a new collection using $out and update an existing collection using $merge.
📋 What You'll Learn
Create an aggregation pipeline on the sales collection.
Group documents by author and sum copies_sold as total_copies.
Use $out to write the grouped results into a new collection called author_sales_summary.
Use $merge to update or insert documents into an existing collection called author_sales_aggregate.
💡 Why This Matters
🌍 Real World
Summarizing sales data by author helps bookstores track popular authors and manage inventory efficiently.
💼 Career
Understanding $out and $merge is essential for database administrators and backend developers who manage data pipelines and reporting in MongoDB.
Progress0 / 4 steps
1
Create the sales collection with sample data
Create a variable called sales and insert these exact documents into it: {"title": "Book A", "author": "Alice", "copies_sold": 5}, {"title": "Book B", "author": "Bob", "copies_sold": 3}, {"title": "Book C", "author": "Alice", "copies_sold": 7}.
MongoDB
Need a hint?

Use db.sales.insertMany([...]) with the exact documents listed.

2
Create the aggregation pipeline to group by author and sum copies sold
Create a variable called pipeline that contains an array with one stage: a $group stage grouping by _id as "$author" and summing copies_sold into total_copies.
MongoDB
Need a hint?

Use $group with _id: "$author" and total_copies: { $sum: "$copies_sold" }.

3
Use $out to write the aggregation results to author_sales_summary
Run db.sales.aggregate() with the pipeline followed by a $out stage that writes to the collection author_sales_summary.
MongoDB
Need a hint?

Add { $out: "author_sales_summary" } as the last stage in the pipeline and run db.sales.aggregate(pipeline).

4
Use $merge to update or insert into author_sales_aggregate
Modify the pipeline by replacing the $out stage with a $merge stage that merges into author_sales_aggregate using _id as the unique key. Then run db.sales.aggregate(pipeline).
MongoDB
Need a hint?

Use $merge with into, on, whenMatched, and whenNotMatched options.