These operators help group data into ranges or buckets to see how values are spread out.
$bucket and $bucketAuto for distribution in MongoDB
Introduction
Syntax
MongoDB
db.collection.aggregate([
{
$bucket: {
groupBy: <expression>,
boundaries: [<lower1>, <lower2>, ..., <upper>],
default: <optional-default-bucket>,
output: { <field1>: { <accumulator1> }, ... }
}
}
])
// or
db.collection.aggregate([
{
$bucketAuto: {
groupBy: <expression>,
buckets: <number-of-buckets>,
output: { <field1>: { <accumulator1> }, ... }
}
}
])$bucket requires you to specify exact boundaries for the groups.
$bucketAuto automatically creates buckets with roughly equal numbers of documents.
Examples
MongoDB
db.sales.aggregate([
{
$bucket: {
groupBy: "$price",
boundaries: [0, 100, 200, 300],
default: "Other",
output: { count: { $sum: 1 } }
}
}
])MongoDB
db.sales.aggregate([
{
$bucketAuto: {
groupBy: "$price",
buckets: 3,
output: { count: { $sum: 1 } }
}
}
])Sample Program
This groups products by quantity in stock into ranges 0-49, 50-99, 100-149, 150+.
MongoDB
db.products.aggregate([
{
$bucket: {
groupBy: "$quantity",
boundaries: [0, 50, 100, 150],
default: "Other",
output: { count: { $sum: 1 } }
}
}
])Important Notes
Use $bucket when you know the exact ranges you want.
Use $bucketAuto when you want MongoDB to decide ranges for balanced groups.
The default bucket catches values less than the first boundary or invalid values in $bucket.
Summary
$bucket groups data by fixed ranges you define.
$bucketAuto groups data into balanced buckets automatically.
Both help understand how data is spread across ranges.
Practice
1. What is the main difference between
$bucket and $bucketAuto in MongoDB aggregation?easy
Solution
Step 1: Understand
$bucketbehavior$bucketrequires explicit boundaries to group documents into fixed ranges.Step 2: Understand
$bucketAutobehavior$bucketAutoautomatically calculates boundaries to create balanced buckets based on data distribution.Final Answer:
$bucketrequires you to specify boundaries;$bucketAutocreates balanced buckets automatically. -> Option AQuick Check:
$bucketvs$bucketAuto= C [OK]
Hint: Remember: manual ranges for $bucket, auto ranges for $bucketAuto [OK]
Common Mistakes:
- Confusing which operator auto-calculates boundaries
- Thinking $bucketAuto needs manual boundaries
- Assuming $bucket works only with strings
2. Which of the following is the correct syntax to use
$bucket in a MongoDB aggregation pipeline?easy
Solution
Step 1: Check required fields for
$bucket$bucketrequiresgroupByandboundaries. Thedefaultfield is optional.Step 2: Identify correct syntax
{ $bucket: { groupBy: "$score", boundaries: [0, 50, 100] } } correctly usesgroupByandboundarieswithout unnecessary fields.Final Answer:
{ $bucket: { groupBy: "$score", boundaries: [0, 50, 100] } } -> Option DQuick Check:
Correct$bucketsyntax = D [OK]
Hint: Remember:
groupBy and boundaries are mandatory for $bucket [OK]Common Mistakes:
- Using
fieldinstead ofgroupBy - Confusing $bucket with $bucketAuto syntax
- Omitting required
boundariesarray
3. Given the collection documents: [{score: 10}, {score: 20}, {score: 55}, {score: 70}, {score: 90}], what will be the output buckets using this aggregation?
{ $bucket: { groupBy: "$score", boundaries: [0, 50, 100], default: "Other", output: { count: { $sum: 1 } } } }medium
Solution
Step 1: Assign documents to buckets by boundaries
Boundaries are [0, 50, 100]. Scores 10, 20 fall into bucket 0-50 (count 2). Scores 55, 70, 90 fall into 50-100 (count 3).Step 2: Check output format
Output counts per bucket: {_id: 0, count: 2} and {_id: 50, count: 3}.Final Answer:
[{_id: 0, count: 2}, {_id: 50, count: 3}] -> Option CQuick Check:
Bucket counts match boundaries = A [OK]
Hint: Count docs per boundary range carefully [OK]
Common Mistakes:
- Mixing counts between buckets
- Misunderstanding boundaries as inclusive/exclusive
- Assuming default bucket is used when not needed
4. You wrote this aggregation but get an error:
{ $bucket: { groupBy: "$age", boundaries: [20, 30, 40], default: "Other" } } The error says: "Boundaries must be sorted in ascending order and unique." What is the likely cause?medium
Solution
Step 1: Understand error message
The error says boundaries must be sorted ascending and unique, so check boundaries array.Step 2: Check boundaries array
If boundaries are not sorted or have duplicates, error occurs. The example boundaries [20, 30, 40] are sorted and unique, so likely in actual code they are not.Final Answer:
Boundaries array is not sorted or has duplicates. -> Option BQuick Check:
Boundaries must be sorted unique = B [OK]
Hint: Check boundaries array order and duplicates first [OK]
Common Mistakes:
- Ignoring error message details
- Thinking default value type causes this error
- Assuming groupBy field type causes this error
5. You want to create 4 buckets automatically for a collection with a wide range of numeric values in field
price. Which aggregation stage correctly achieves this using $bucketAuto?hard
Solution
Step 1: Identify correct
$bucketAutousage$bucketAutorequiresgroupByandbuckets(number). { $bucketAuto: { groupBy: "$price", buckets: 4, output: { count: { $sum: 1 }, avgPrice: { $avg: "$price" } } } } uses these correctly and includes output aggregation.Step 2: Eliminate incorrect options
{ $bucket: { groupBy: "$price", boundaries: [0, 25, 50, 75, 100] } } uses$bucketwith manual boundaries, not automatic. { $bucketAuto: { groupBy: "$price", boundaries: [0, 25, 50, 75, 100] } } incorrectly uses boundaries with$bucketAuto. { $bucketAuto: { groupBy: "$price", buckets: "4" } } uses string for buckets count, which must be a number.Final Answer:
{ $bucketAuto: { groupBy: "$price", buckets: 4, output: { count: { $sum: 1 }, avgPrice: { $avg: "$price" } } } } -> Option AQuick Check:
Correct$bucketAutosyntax with numeric buckets = A [OK]
Hint: Use numeric buckets count and no boundaries with $bucketAuto [OK]
Common Mistakes:
- Using boundaries with $bucketAuto
- Passing buckets as string instead of number
- Confusing $bucket and $bucketAuto syntax
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
