QA
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→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?