How to Group MongoDB Records by Hour in Code (Node.js)?

Hi all,

I’m working on a Node.js app that logs user actions with timestamps in MongoDB. I want to generate hourly activity summaries — basically group records by hour of the day (e.g. 13:00–14:00, 14:00–15:00, etc.) and count how many actions happened in each hour.

Here’s a simplified structure of my documents:

{
  "userId": "abc123",
  "action": "login",
  "timestamp": ISODate("2025-07-13T13:45:00Z")
}

In my aggregation pipeline, I’m using $hour: “$timestamp” but the groupings feel off, possibly due to timezone differences. I’m also not sure if I should handle the hour extraction in the aggregation pipeline or in the application code.

Is there a preferred way to group by local hour using MongoDB aggregation within Node.js (e.g., with the native driver or Mongoose)?

Any suggestions or sample code would be appreciated!

Thanks,
Jhonn Mick

Hi @Jhonn_Marie, so as you’ve said, the $hour operator is off due to timezone differences, so to get around this, you can use the $dateTrunc operator and it works from MongoDB 5.0+.

This is how it would work in your use-case -

db.collection.aggregate([
  {
    $group: {
      _id: {
        $dateTrunc: {
          date: "$timestamp",
          unit: "hour",
          timezone: "Your/Timezone"
        }
      },
      count: { $sum: 1 }
    }
  },
  {
    $sort: { _id: 1 } // sort by hour
  }
])

This link also gives you more information to how $dateTrunc works -

1 Like

Thanks a ton, Michael! That’s exactly what I needed. I didn’t realize $dateTrunc handled timezone offsets so cleanly, super helpful. I’ll give this a try with my local timezone and see how it goes. Really appreciate you including the example too!

2 Likes