$isoWeek (aggregation)

Definition

  • $isoWeek

New in version 3.4.

Returns the week number in ISO 8601 format, ranging from 1 to53. Week numbers start at 1 with the week (Monday throughSunday) that contains the year’s first Thursday.

The $isoWeek expression has the followingoperator expression syntax:

  1. { $isoWeek: <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. { $isoWeek: { date: new Date("Jan 4, 2016") } }
1
  1. { $isoWeek: new Date("2016-01-01") }
53
  1. { $isoWeek: { date: new Date("August 14, 2011"), timezone: "America/Chicago"} }
32
  1. { $isoWeek: ISODate("1998-11-02T00:00:00Z") }
45
  1. { $isoWeek: { date: ISODate("1998-11-02T00:00:00Z"), timezone: "-0500"} }
44
  1. { $isoWeek: "March 28, 1976" }
error
  1. { $isoWeek: Date("2016-01-01") }
error
  1. { $isoWeek: "2009-04-09" }
error

Note

$isoWeek cannot take a string as an argument.

Example

A collection called deliveries contains the following documents:

  1. { "_id" : 1, "date" : ISODate("2006-10-24T00:00:00Z"), "city" : "Boston" }
  2. { "_id" : 2, "date" : ISODate("2011-08-18T00:00:00Z"), "city" : "Detroit" }

The following operation returns the week number for each date field.

  1. db.deliveries.aggregate( [
  2. {
  3. $project: {
  4. _id: 0,
  5. city: "$city",
  6. weekNumber: { $isoWeek: "$date" }
  7. }
  8. }
  9. ] )

The operation returns the following results:

  1. { "city" : "Boston", "weekNumber" : 43 }
  2. { "city" : "Detroit", "weekNumber" : 33 }

See also