0
0
MongoDBquery~30 mins

$bucket and $bucketAuto for distribution in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$bucket and $bucketAuto for distribution in MongoDB
📖 Scenario: You work for a bookstore that wants to analyze how many books fall into different price ranges. You have a collection of books with their prices, and you want to group these books into price buckets to understand the distribution.
🎯 Goal: Build two MongoDB aggregation queries: one using $bucket to manually define price ranges, and another using $bucketAuto to automatically create price buckets. This will help the bookstore see how books are distributed by price.
📋 What You'll Learn
Create a collection called books with documents containing title and price fields.
Write an aggregation query using $bucket to group books into these price ranges: 0-10, 10-20, 20-30, and 30 and above.
Write an aggregation query using $bucketAuto to automatically create 4 buckets based on book prices.
Use count to see how many books fall into each bucket.
💡 Why This Matters
🌍 Real World
Bookstores and retailers often want to understand how products are priced and distributed across price ranges to make pricing and marketing decisions.
💼 Career
Data analysts and database developers use $bucket and $bucketAuto in MongoDB to group and summarize data efficiently for reports and dashboards.
Progress0 / 4 steps
1
Create the books collection with sample data
Insert these exact documents into a MongoDB collection called books: { title: 'Book A', price: 5 }, { title: 'Book B', price: 12 }, { title: 'Book C', price: 25 }, { title: 'Book D', price: 35 }, { title: 'Book E', price: 8 }.
MongoDB
Need a hint?

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

2
Define the price boundaries for manual bucketing
Create a variable called priceBoundaries and set it to the array [0, 10, 20, 30, 1000] to define the price ranges for bucketing.
MongoDB
Need a hint?

Define priceBoundaries as an array with the exact values.

3
Write the aggregation query using $bucket
Write an aggregation query on books using $bucket with groupBy set to $price, boundaries set to priceBoundaries, and default set to 'Other'. Include a count field that sums 1 for each book in the bucket.
MongoDB
Need a hint?

Use db.books.aggregate([{ $bucket: { groupBy: "$price", boundaries: priceBoundaries, default: "Other", output: { count: { $sum: 1 } } } }]).

4
Write the aggregation query using $bucketAuto
Write an aggregation query on books using $bucketAuto with groupBy set to $price and buckets set to 4. Include a count field that sums 1 for each book in the bucket.
MongoDB
Need a hint?

Use db.books.aggregate([{ $bucketAuto: { groupBy: "$price", buckets: 4, output: { count: { $sum: 1 } } } }]).