$hour (Get Hour)

Last updated: 2026-10-09

$hour (Get Hour)

$hour returns the hour part of a date (0 to 23) — common for hourly traffic analysis, alert windows, or hourly reports. It returns an integer in 24-hour format. timezone matters most here: UTC plus 8 hours gives Beijing time, so cross-zone analysis must set timezone explicitly or every bucket shifts. Defaults to UTC.

CategoryDate
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $hour: { date: <date-expression>, timezone: <timezone> } }

⚙️ Parameters

dateRequired; the date expression.
timezoneOptional timezone; defaults to UTC.

Returns:The hour (0-23); null if date is null.

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $hour: visits by hour (Beijing time)
 db.visits.aggregate([
  { $group: {
      _id: { $hour: { date: '$visitAt', timezone: 'Asia/Shanghai' } },
      pv: { $sum: 1 }
  } }
])

Output:

{ "_id": 9, "pv": 2300 }
{ "_id": 10, "pv": 3100 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QWhat is the range?
A0 to 23, 24-hour format.
QWhy is my hourly data shifted?
ALikely timezone — pass a local zone like 'Asia/Shanghai'.
QCan I output two-digit hours like 09?
AUse the %H placeholder of $dateToString.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏