$isoWeek (aggregation)

On this page本页内容

Definition定义

$isoWeek

New in version 3.4.版本3.4中的新功能。

Returns the week number in ISO 8601 format, ranging from 1 to 53. 返回ISO 8601格式的周数,范围从153Week numbers start at 1 with the week (Monday through Sunday) that contains the year’s first Thursday.周数从1开始,以包含一年中第一个星期四的一周(周一到周日)为单位。

The $isoWeek expression has the following operator expression syntax:$isoWeek表达式具有以下运算符表达式语法

{ $isoWeek: <dateExpression> }

Changed in version 3.6.在版本3.6中更改。

The argument must be a valid expression that resolves to one of the following:参数必须是解析为以下之一的有效表达式

  • A Date, a Timestamp, or an ObjectID.DateTimestampObjectID
  • A document of the following form:以下形式的文件:

    New in version 3.6.版本3.6中的新功能。

    { date: <dateExpression>, timezone: <tzExpression> }
    Field字段Description描述
    date The date to which the operator is applied. 应用运算符的日期。<dateExpression> must be a valid expression that resolves to a Date, a Timestamp, or an ObjectID.<dateExpression>必须是解析为DateTimestampObjectID的有效表达式
    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. <tzExpression>必须是有效的表达式,可以解析为格式为奥尔逊时区标识符UTC偏移量的字符串。If no timezone is provided, the result is displayed in UTC.如果未提供timezone,结果将以UTC显示。

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

Note

$isoWeek cannot take a string as an argument.不能将字符串作为参数。

Example示例

A collection called deliveries contains the following documents:名为deliveries的集合包含以下文档:

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

The following operation returns the week number for each date field.以下操作返回每个date字段的周数。

db.deliveries.aggregate( [
  {
    $project: {
      _id: 0,
      city: "$city",
      weekNumber: { $isoWeek: "$date" }
    }
  }
] )

The operation returns the following results:操作返回以下结果:

{ "city" : "Boston", "weekNumber" : 43 }
{ "city" : "Detroit", "weekNumber" : 33 }