amazingdoodler
amazingdoodler

Reputation: 73

How can I aggregate MongoDB documents by hour?

I have documents in a collection called "files" in MongoDB 5.0.2. This collection is for user uploaded content. I want to get a count of the number of files uploaded within the last 24 hours at a 1 hour interval.

For example, user uploaded 3 files at 13:00, 2 files at 14:00, 0 files at 15:00, and so on.

I already store a "timestamp" field in my Mongo documents which is an ISODate object from Javascript.

I have looked at countless stackoverflow questions but I cannot find anything that fits my needs or that I understand.

Upvotes: 0

Views: 544

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59436

Would be this one:

{ $match: {timestamp: {$gt: moment().startOf('hour').subtract(24, 'hours').toDate() } } }, 
{ $group:
  _id: {
    y: {$year: "$timestamp"},
    m: {$month: "$timestamp"},
    d: {$dayOfMonth: "$timestamp"},
    h: {$hour: "$timestamp"},
  },
  count: ...
}

or in Mongo version 5.0 you can do

{ $group:
  _id: { $dateTrunc: { date: "$timestamp", unit: "hour" } },
  count: ...
}

For any datetime related operations I recommend the moment.js library

Upvotes: 1

Related Questions