$hour (aggregation)
定义
$hour
返回日期的小时部分,数值介于0到23之间。
{ $hour: <dateExpression> } 参数可以是
具有以下格式的文档
{ date: <dateExpression>, timezone: <tzExpression> } 字段描述date
timezone
可选。操作结果的时区。必须使用有效的
<tzExpression>
表达式,该表达式解析为以下格式的字符串:Olson 时区标识符或UTC偏移量。如果未提供时区,则结果为UTC。格式示例Olson 时区标识符
"America/New_York" "Europe/London" "GMT" UTC 偏移量
+/-[hh]:[mm], e.g. "+04:45" +/-[hh][mm], e.g. "-0530" +/-[hh], e.g. "+03"
行为
示例 | 结果 | ||||
---|---|---|---|---|---|
| 12 | ||||
| 0 | ||||
| 19 | ||||
| 0 | ||||
| 5 | ||||
| 错误 | ||||
| 错误 | ||||
| 错误 |
注意
$hour 不能接受字符串作为参数。
示例
考虑一个包含以下文档的 销售
集合
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:15:39.736Z") }
以下聚合操作使用了 $hour
和其他日期表达式来分解 日期
字段
db.sales.aggregate( [ { $project: { year: { $year: "$date" }, month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, hour: { $hour: "$date" }, minutes: { $minute: "$date" }, seconds: { $second: "$date" }, milliseconds: { $millisecond: "$date" }, dayOfYear: { $dayOfYear: "$date" }, dayOfWeek: { $dayOfWeek: "$date" } } } ] )
该操作返回以下结果
{ "_id" : 1, "year" : 2014, "month" : 1, "day" : 1, "hour" : 8, "minutes" : 15, "seconds" : 39, "milliseconds" : 736, "dayOfYear" : 1, "dayOfWeek" : 4, "week" : 0 }