MongoDB $hour Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Date Operations

What You’ll Learn

The $hour operator extracts the hour (0–23) from a BSON Date inside MongoDB aggregation pipelines. Use it for peak-traffic analysis, business-hours filtering, hourly dashboards, and time-of-day reporting.

01

Extract Hour

Date → integer 0–23.

02

Syntax

One date argument.

03

Timezone Option

Local hour support.

04

UTC Default

0–23 in UTC.

05

Use Cases

Traffic, shifts.

06

Related Ops

$minute, $dateTrunc.

Definition and Usage

In MongoDB’s aggregation framework, the $hour operator takes a date expression and returns an integer between 0 and 23. For example, $hour applied to ISODate("2024-06-15T14:30:00Z") returns 14, and ISODate("2024-06-15T02:15:00Z") returns 2.

💡
Beginner Tip

$hour uses UTC by default. For business-hours logic in a local timezone, use the object form with a timezone option (see Example 4).

📝 Syntax

The $hour operator takes a date expression, or an object with date and timezone:

mongosh
{ $hour: <dateExpression> }

// With timezone:
{
  $hour: {
    date: <dateExpression>,
    timezone: <tz>
  }
}

Syntax Rules

  • Argument — any expression that evaluates to a BSON Date (field, $$NOW, or literal).
  • Return value — integer from 0 to 23 (midnight is 0, 11 PM is 23).
  • Null input — returns null when the date is null or missing.
  • Timezone — optional; use Olson timezone IDs like "America/New_York".
  • Use inside $project, $addFields, $set, $match (with $expr), or $group.

💡 $hour vs $minute vs $dateTrunc

$hour — BSON Date → integer 0–23 (hour component)
$minute — BSON Date → integer 0–59 (minute component)
$dateTrunc — BSON Date → Date at period boundary (great for hourly buckets)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (date extraction)
ArgumentsOne date expression
Return typeInteger (0–23)
Timezone supportYes (object form with timezone)
MongoDB version3.4+
From field
{ $hour: "$loggedAt" }

Hour component

2:30 PM UTC
{ $hour: ISODate("2024-06-15T14:30:00Z") }

Returns 14

In $project
{
  hour: { $hour: "$eventAt" }
}

Add computed field

With timezone
{
  $hour: {
    date: "$eventAt",
    timezone: "America/New_York"
  }
}

Local hour

Examples Gallery

Extract hour values, filter business-hours events, group traffic by hour, and read hours in a local timezone with $hour.

📚 Extract Hour from a Date Field

Use a logs collection and compute the hour from loggedAt.

Sample Input Documents

Suppose you have a logs collection with timestamps:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "action": "login",
    "loggedAt": ISODate("2024-06-15T09:30:00Z")
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "action": "purchase",
    "loggedAt": ISODate("2024-06-15T14:45:00Z")
  }
]

Example 1 — Add hour with $hour

Extract the hour component from each timestamp:

mongosh
db.logs.aggregate([
  {
    $project: {
      action: 1,
      loggedAt: 1,
      hour: { $hour: "$loggedAt" }
    }
  }
])

How It Works

  • 09:30 UTC → hour 9.
  • 14:45 UTC → hour 14.
  • Minutes and seconds are ignored — only the hour is returned.

📈 Practical Patterns

Business-hours filters, hourly grouping, and timezone-aware extraction.

Example 2 — Filter Events During Business Hours (9 AM – 5 PM)

Find logs between 9:00 and 17:59 UTC using $expr:

mongosh
db.logs.find({
  $expr: {
    $and: [
      { $gte: [ { $hour: "$loggedAt" }, 9 ] },
      { $lte: [ { $hour: "$loggedAt" }, 17 ] }
    ]
  }
})

How It Works

Combine $hour with $gte and $lte inside $expr. This matches any event from 9:00 through 17:59 (hour 17 includes 5:00–5:59 PM).

Example 3 — Group Page Views by Hour of Day

Analyze peak traffic hours across all days:

mongosh
db.pageviews.aggregate([
  {
    $group: {
      _id: { $hour: "$viewedAt" },
      views: { $sum: 1 }
    }
  },
  { $sort: { "_id": 1 } }
])

How It Works

Grouping by $hour aggregates all days together — useful for “which hour of the day is busiest?” charts. Add $dateTrunc if you need per-day hourly buckets instead.

Example 4 — Hour in a Specific Timezone

Extract the hour in Eastern Time rather than UTC:

mongosh
db.logs.aggregate([
  {
    $project: {
      action: 1,
      loggedAt: 1,
      hourUtc: { $hour: "$loggedAt" },
      hourEastern: {
        $hour: {
          date: "$loggedAt",
          timezone: "America/New_York"
        }
      }
    }
  }
])

// loggedAt: 2024-06-15T14:30:00Z
// hourUtc: 14, hourEastern: 10 (EDT)

How It Works

The object form with timezone converts the instant to the specified zone before extracting the hour. Use this when business rules follow local time, not UTC.

🚀 Use Cases

  • Peak traffic analysis — group events by hour to find busiest times of day.
  • Business hours filtering — select logs or orders during working hours.
  • Shift scheduling — categorize records into morning, afternoon, or night shifts.
  • SLA monitoring — flag incidents outside support hours using hour ranges.

🧠 How $hour Works

1

MongoDB resolves the date

The input expression is evaluated per document — a field, $$NOW, or literal ISODate.

Input
2

$hour extracts the hour

MongoDB reads the hour component as an integer 0–23 (UTC or specified timezone).

Extract
3

An integer is returned

The number is ready for $match, $group, or charts.

Output
=

Hour for time-of-day analytics

Combine with $minute, $dayOfWeek, and $dateTrunc for richer time reporting.

Conclusion

The $hour operator is a simple way to extract the hour component from BSON dates in MongoDB aggregation pipelines. It is especially useful for peak-traffic charts, business-hours filters, and hourly dashboards.

Remember it uses UTC by default. For local business hours, pass a timezone in the object form. Next in the series: $ifNull.

💡 Best Practices

✅ Do

  • Use the timezone option for local business-hour logic
  • Combine with $gte and $lte for hour ranges
  • Use $expr when filtering by $hour in find()
  • Prefer BSON dates over strings for reliable extraction
  • Pair with $dateTrunc when you need hourly date buckets

❌ Don’t

  • Assume UTC hour matches local business hours
  • Confuse $hour with $dateTrunc hourly bucketing
  • Use $hour on string dates — parse first with $dateFromString
  • Forget that hour 0 is midnight and hour 23 is 11 PM
  • Expect minutes to affect the result — only the hour is returned

Key Takeaways

Knowledge Unlocked

Five things to remember about $hour

Use these points when extracting hours from dates in MongoDB.

5
Core concepts
📝 02

One Argument

Date expression.

Syntax
🛠 03

Integer Output

Not a Date.

Output
🌐 04

Timezone Option

Local hour support.

Note
05

UTC Default

0 = midnight UTC.

Important

❓ Frequently Asked Questions

$hour returns an integer from 0 to 23 representing the hour portion of a BSON Date. For example, 2:30 PM UTC returns 14.
Simple form: { $hour: <dateExpression> }. With timezone: { $hour: { date: <dateExpression>, timezone: <tz> } }. Pass a field like "$loggedAt" or a literal ISODate.
By default, $hour uses UTC. To get the hour in a specific timezone, use the object form with a timezone string like "America/New_York".
$hour returns an integer 0–23 for the hour component. $dateTrunc returns a Date rounded down to a period boundary (hour, day, month) — better for grouping into time buckets.
$hour is available in MongoDB 3.4 and later in aggregation pipelines and update pipelines that use aggregation expressions.

Continue the Operator Series

Move on to $ifNull for null handling, or review $dateTrunc to bucket dates into hourly periods.

Next: $ifNull →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful