$year(聚合)
定义
$year
返回日期的年份部分。
{ $year: <dateExpression> } 参数可以是
具有此格式的文档
{ date: <dateExpression>, timezone: <tzExpression> } 字段描述date
timezone
可选。运算结果的时间区域。
<tzExpression>
必须是一个有效的 表达式,该表达式解析为格式化为 Olson 时间区域标识符的字符串或 UTC 偏移量。如果没有提供timezone
,则结果为 UTC。格式示例Olson 时间区域标识符
"America/New_York" "Europe/London" "GMT" UTC 偏移量
+/-[hh]:[mm], e.g. "+04:45" +/-[hh][mm], e.g. "-0530" +/-[hh], e.g. "+03"
行为
示例 | 结果 | ||||
---|---|---|---|---|---|
| 2016 | ||||
| 2003 | ||||
| 2011 | ||||
| 1998 | ||||
| 1998 | ||||
| 错误 | ||||
| 错误 | ||||
| 错误 |
注意
$year 不能接受字符串作为参数。
示例
考虑一个具有以下文档的 销售
收集
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:15:39.736Z") }
以下聚合使用 $year
和其他日期运算符来分解 日期
字段
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" }, week: { $week: "$date" } } } ] )
操作返回以下结果
{ "_id" : 1, "year" : 2014, "month" : 1, "day" : 1, "hour" : 8, "minutes" : 15, "seconds" : 39, "milliseconds" : 736, "dayOfYear" : 1, "dayOfWeek" : 4, "week" : 0 }