$year (aggregation)
On this page
Definition
$year
Returns the year portion of a date.
The
$year
expression has the following operator expression syntax:{ $year: <dateExpression> } The argument can be:
An expression that resolves to a Date, a Timestamp, or an ObjectID.
A document with this format:
{ date: <dateExpression>, timezone: <tzExpression> } FieldDescriptiondate
The date to which the operator is applied.<dateExpression>
must be a valid expression that resolves to a Date, a Timestamp, or an ObjectID.timezone
Optional. The timezone of the operation result.
<tzExpression>
must be a valid expression that resolves to a string formatted as either an Olson Timezone Identifier or a UTC Offset. If notimezone
is provided, the result is in UTC.FormatExamplesOlson Timezone Identifier
"America/New_York" "Europe/London" "GMT" UTC Offset
+/-[hh]:[mm], e.g. "+04:45" +/-[hh][mm], e.g. "-0530" +/-[hh], e.g. "+03"
Behavior
Example | Result | ||||
---|---|---|---|---|---|
| 2016 | ||||
| 2003 | ||||
| 2011 | ||||
| 1998 | ||||
| 1998 | ||||
| error | ||||
| error | ||||
| error |
Note
$year cannot take a string as an argument.
Example
Consider a sales
collection with the following documents:
{ "_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:
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 }