本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$hour
运$hour算符从日期或时间戳字段中提取小时部分。
参数
-
dateExpression:运算符的应用日期。这必须解析为有效的 BSON 日期(例如,像 $createdAt 这样的字段或日期文字)。
也可以按以下格式将参数指定为文档:
{日期:<dateExpression>,时区:<timezoneExpression>}
这允许应用时区感知日期操作。
- `<tzExpression>`: (optional) The timezone of the operation result. It must be a valid expression that resolves to a string formatted as either an Olson Timezone Identifier or a UTC Offset. If no timezone is provided, the result is in UTC.
示例(MongoDB 外壳)
以下示例演示如何使用$hour运算符从日期字段中提取小时分量并相应地对数据进行分组。
创建示例文档
db.events.insertMany([ { timestamp: new Date("2023-04-01T10:30:00Z") }, { timestamp: new Date("2023-04-01T12:45:00Z") }, { timestamp: new Date("2023-04-02T08:15:00Z") }, { timestamp: new Date("2023-04-02T16:20:00Z") }, { timestamp: new Date("2023-04-03T23:59:00Z") } ]);
查询示例
db.events.aggregate([ { $project: { hour: { $hour: "$timestamp" } } }, { $group: { _id: "$hour", count: { $sum: 1 } } }, { $sort: { _id: 1 } } ]);
输出
[
{ "_id": 8, "count": 1 },
{ "_id": 10, "count": 1 },
{ "_id": 12, "count": 1 },
{ "_id": 16, "count": 1 },
{ "_id": 23, "count": 1 }
]
此查询按timestamp字段的小时部分对事件进行分组,并计算每小时的事件数。
代码示例
要查看使用该$hour命令的代码示例,请选择要使用的语言的选项卡: