Want to group documents by range? $bucket makes it easy

Darshit AnjariaDarshit Anjaria
3 min read

Hey devs! 👋

Today, we’re diving into one of MongoDB’s powerful aggregation stages — the one that helps us group and organize our data just the way we need it. Let’s break it down together! 💡


When working with MongoDB, sometimes we need to group documents by a specific range, like age brackets, price categories, or date intervals. If you've ever wanted to categorize or bucket your data into ranges for better analytics, MongoDB offers the perfect solution with the $bucket aggregation stage.

Let’s break it down in a simple and practical way.


What is the $bucket Stage? 🪣

The $bucket stage is part of MongoDB’s Aggregation Pipeline, used to group documents into defined intervals, known as buckets.

Think of $bucket as a way to manually divide data into custom groups based on the boundaries you set. Each document will be placed into one of the buckets depending on the value of a specified field.


Why & Where Is $bucket Used? 🤔

$bucket is commonly used when:

  • You want to group numerical or date-based data into predefined categories

  • You need custom range-based aggregation

  • You want to generate histogram-style data reports

  • You’re working on analytics dashboards or reports


Real-World Scenario: E-commerce Order Pricing 🌍

Imagine you're building an analytics dashboard for an e-commerce platform. You want to analyze how many customer orders fall into different price ranges, such as:

  • Under $50

  • $50 to $100

  • $100 to $200

  • Above $200

This is a classic use case for $bucket.


Example Pipeline Using $bucket 🧪

Here’s how a simple pipeline using $bucket would look:

db.orders.aggregate([
  {
    $bucket: {
      groupBy: "$totalAmount", // Field to group by
      boundaries: [0, 50, 100, 200, 1000], // Bucket boundaries
      default: "Other", // Where to put values not fitting any range
      output: {
        count: { $sum: 1 }, // Count documents per bucket
        averageAmount: { $avg: "$totalAmount" }, // Avg. total per bucket
      },
    },
  },
]);

What this does🧾

  • Groups all orders by the totalAmount field

  • Creates buckets: [0–50), [50–100), [100–200), [200–1000)

  • Any order not falling within these ranges will be placed in the "Other" bucket

  • For each bucket, it calculates the number of orders and their average amount


Benefits of Using $bucket

  • Easy and readable way to group numeric or date values

  • Helps in building range-based summaries

  • Very useful for dashboards, reporting, and data analytics


Learn More 🔗

MongoDB’s official documentation provides even more insights and advanced options for $bucket.

👉 More info here: MongoDB $bucket Stage Documentation


Bonus Tip: What’s the difference between $bucket and $bucketAuto?

While $bucket requires manual boundary definitions, $bucketAuto allows MongoDB to automatically create buckets of equal document counts — perfect when you don’t know the ranges in advance.


MongoDB's $bucket stage is a great way to simplify categorical grouping when working with ranges. Whether it’s order values, user ages, or event timestamps, this stage helps you organize and analyze your data with clarity and precision.


Thank You!

Thank you for reading!
I hope you enjoyed this post. If you did, please share it with your network and stay tuned for more insights on software development. I'd love to connect with you on LinkedIn or have you follow my journey on HashNode for regular updates.

Happy Coding!
Darshit Anjaria

0
Subscribe to my newsletter

Read articles from Darshit Anjaria directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Darshit Anjaria
Darshit Anjaria

I’m a problem solver at heart, driven by the idea of building solutions that genuinely make a difference in people’s everyday lives. I’m always curious, always learning, and always looking for ways to improve the world around me through thoughtful, impactful work. Beyond building, I love giving back to the community — whether it’s by sharing what I’ve learned through blogs, tutorials, or helpful insights. My goal is simple: to make technology a little more accessible and useful for everyone. Let’s learn, build, and grow together.