On this page本页内容
$year
Returns the year portion of a date.返回日期的年份部分。
The $year
expression has the following operator expression syntax:$year
表达式具有以下运算符表达式语法:
{ $year: <dateExpression> }
The argument can be:参数可以是:
A document with this format:具有以下格式的文档:
{ date: <dateExpression>, timezone: <tzExpression> }
date | <dateExpression> | ||||||
timezone |
|
{ $year: new Date("2016-01-01") } | 2016 |
{ $year: { date: new Date("Jan 7, 2003") } } | 2003 |
{ $year: { date: new Date("August 14, 2011"), timezone: "America/Chicago" } } | 2011 |
{ $year: ISODate("1998-11-07T00:00:00Z") } | 1998 |
{ $year: { date: ISODate("1998-11-07T00:00:00Z"), timezone: "-0400" } } | 1998 |
{ $year: "March 28, 1976" } | error |
{ $year: Date("2016-01-01") } | error |
{ $year: "2009-04-09" } | error |
$year
Consider a 考虑使用以下文档的sales
collection with the following documents:sales
集合:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:15:39.736Z") }
The following aggregation uses the 以下聚合使用$year
and other date operators to break down the date
field:$year
和其他日期运算符细分date
字段:
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" } } } ] )
The operation returns the following result:该操作返回以下结果:
{ "_id" : 1, "year" : 2014, "month" : 1, "day" : 1, "hour" : 8, "minutes" : 15, "seconds" : 39, "milliseconds" : 736, "dayOfYear" : 1, "dayOfWeek" : 4, "week" : 0 }