$year (aggregation)

Definition

  • $year
  • Returns the year portion of a date.

The $year expression has the followingoperator expression syntax:

  1. { $year: <dateExpression> }

Changed in version 3.6.

The argument must be a valid expression that resolves to one of the following:

New in version 3.6.

  1. { date: <dateExpression>, timezone: <tzExpression> }

FieldDescriptiondateThe date to which the operator is applied.<dateExpression> must be a valid expression that resolves to aDate, aTimestamp,or an ObjectID.timezoneOptional. The timezone of the operation result.<tzExpression> must be a valid expression that resolves to a string formatted as eitheran Olson Timezone Identifier or aUTC Offset.If no timezone is provided, the result is displayed in UTC.

FormatExamplesOlson Timezone Identifier

  1. "America/New_York"
  2. "Europe/London"
  3. "GMT"

UTC Offset

  1. +/-[hh]:[mm], e.g. "+04:45"
  2. +/-[hh][mm], e.g. "-0530"
  3. +/-[hh], e.g. "+03"

Behavior

ExampleResult
  1. { $year: new Date("2016-01-01") }
2016
  1. { $year: { date: new Date("Jan 7, 2003") } }
2003
  1. { $year: { date: new Date("August 14, 2011"), timezone: "America/Chicago"} }
2011
  1. { $year: ISODate("1998-11-07T00:00:00Z") }
1998
  1. { $year: { date: ISODate("1998-11-07T00:00:00Z"), timezone: "-0400"} }
1998
  1. { $year: "March 28, 1976" }
error
  1. { $year: Date("2016-01-01") }
error
  1. { $year: "2009-04-09" }
error

Note

$year cannot take a string as an argument.

Example

Consider a sales collection with the following documents:

  1. {
  2. "_id" : 1,
  3. "item" : "abc",
  4. "price" : 10,
  5. "quantity" : 2,
  6. "date" : ISODate("2014-01-01T08:15:39.736Z")
  7. }

The following aggregation uses the $year and otherdate operators to break down the date field:

  1. db.sales.aggregate(
  2. [
  3. {
  4. $project:
  5. {
  6. year: { $year: "$date" },
  7. month: { $month: "$date" },
  8. day: { $dayOfMonth: "$date" },
  9. hour: { $hour: "$date" },
  10. minutes: { $minute: "$date" },
  11. seconds: { $second: "$date" },
  12. milliseconds: { $millisecond: "$date" },
  13. dayOfYear: { $dayOfYear: "$date" },
  14. dayOfWeek: { $dayOfWeek: "$date" },
  15. week: { $week: "$date" }
  16. }
  17. }
  18. ]
  19. )

The operation returns the following result:

  1. {
  2. "_id" : 1,
  3. "year" : 2014,
  4. "month" : 1,
  5. "day" : 1,
  6. "hour" : 8,
  7. "minutes" : 15,
  8. "seconds" : 39,
  9. "milliseconds" : 736,
  10. "dayOfYear" : 1,
  11. "dayOfWeek" : 4,
  12. "week" : 0
  13. }