$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.
| Category | Date |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $hour: { date: <date-expression>, timezone: <timezone> } }
⚙️ Parameters
| date | Required; the date expression. |
|---|---|
| timezone | Optional 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
- 24-hour format, range 0-23
- Timezone shifts hours as a whole: at 8 in UTC+8, UTC is still 0
- For business semantics like "what hour", always pass timezone
🏷️ Related Tags
💡 Related Cases
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.