Intermediate LevelMongoDB & Mongoose
How does the $bucket stage group numerical and time-series data ranges?
❓ Interview Prompt: Explain $bucket stage, numerical and date range boundaries, default fallback bucket, and calculating metrics per interval.
The '$bucket' stage categorizes incoming documents into specified numerical or date range boundaries, aggregating metrics per bucket interval:
Use Cases:
Grouping e-commerce products into price ranges ($0-$50, $50-$100, $100+) or telemetry metrics into hourly buckets.
Code Implementation Example
typescript
import { ProductModel } from './models/Product';
async function groupProductsByPriceBucket() {
const result = await ProductModel.aggregate([
{
$bucket: {
groupBy: '$price',
boundaries: [0, 50, 100, 500, 1000],
default: 'Other',
output: {
count: { $sum: 1 },
products: { $push: '$name' }
}
}
}
]);
return result;
}💡Categorizing products into price range buckets using $bucket.
🎯 Interview Key Takeaway
Use $bucket to aggregate documents into custom numerical or date range buckets.
#$bucket#Aggregation#Histograms#Intermediate
Back to all MongoDB & Mongoose Questions→