How .aggregate() Powered Our Learner & Income Analytics in MongoDB

This week, I worked on something exciting: reports routes for our backend. This is the part of the system that helps admins see important data at a glance. My job was to build endpoints that could transform raw learner and payment data into meaningful insights, including:

  • A list of all learners
  • The number of learners per track
  • The total income
  • The income per track

In short, I wasn’t just fetching data anymore. I was shaping it into something an admin could actually use to make decisions.

Pretty straightforward on paper, but here’s where the twist came in. I had to use MongoDB’s .aggregate() for the first time.

Before this, I had been living in the world of .find() and .findOne(). They were my comfort zone; very simple, direct, and predictable. But for this task, I needed more power: grouping data, filtering it, reshaping fields, and running calculations all in one go. That’s where .aggregate() stepped in.

One of my tasks was to get the number of learners in each track only if they had paid. With .aggregate(), I learned I could:

  1. Filter with $match
  2. Group with $group
  3. Count or sum fields using $sum
  4. Reshape or limit fields with $project

Here’s a little snippet from what I wrote:

const result = await learnerModel.aggregate([
  { $match: { status: 'paid' } },
  {
    $group: {
      _id: "$track",
      count: { $sum: 1 }
    }
  },
  {
    $project: {
      track: "$_id",
      count: 1,
      _id: 0
    }
  }
]);

In this example, $project let me clean up the output by renaming _id to track and hiding unnecessary fields.

Seeing the data come out exactly as I needed — filtered, grouped, and neatly shaped — felt so satisfying. It was like discovering that MongoDB had been quietly hiding a mini data-analytics tool inside it all along.

This experience was more than just adding new routes. I learned a new way of thinking about database queries, and I’m already imagining all the other problems .aggregate() could help me solve.

Similar Posts