$dateFromString (aggregation)

On this page本页内容

Definition定义

$dateFromString

Converts a date/time string to a date object.将日期/时间字符串转换为日期对象。

The $dateFromString expression has the following syntax:$dateFromString表达式语法如下:

{ $dateFromString: {
     dateString: <dateStringExpression>,
     format: <formatStringExpression>,
     timezone: <tzExpression>,
     onError: <onErrorExpression>,
     onNull: <onNullExpression>
} }

The $dateFromString takes a document with the following fields:$dateFromString接受具有以下字段的文档:

Field字段Description描述
dateString

The date/time string to convert to a date object. 要转换为日期对象的日期/时间字符串。See Date for more information on date/time formats.有关日期/时间格式的更多信息,请参阅Date

Note注意

If specifying the timezone option to the operator, do not include time zone information in the dateString.如果为运算符指定timezone选项,请不要在dateString中包含时区信息。

format

Optional. 可选。The date format specification of the dateString. dateString的日期格式规范。The format can be any expression that evaluates to a string literal, containing 0 or more format specifiers. format可以是任何计算为字符串文字的表达式,包含0个或多个格式说明符。For a list of specifiers available, see Format Specifiers.有关可用说明符的列表,请参阅格式说明符

If unspecified, $dateFromString uses "%Y-%m-%dT%H:%M:%S.%LZ" as the default format.如果未指定,$dateFromString使用"%Y-%m-%dT%H:%M:%S.%LZ"作为默认格式。

New in version 4.0.在版本4.0中新增

timezone

Optional. 可选。The time zone to use to format the date.用于设置日期格式的时区。

Note注意

If the dateString argument is formatted like '2017-02-08T12:10:40.787Z', in which the 'Z' at the end indicates Zulu time (UTC time zone), you cannot specify the timezone argument.如果dateString参数的格式为“2017-02-08T12:10:40.787Z”,其中末尾的“Z”表示祖鲁时间(UTC时区),则无法指定timezone参数。

<timezone> allows for the following options and expressions that evaluate to them:允许以下选项和表达式对其求值:

  • an Olson Timezone Identifier, such as "Europe/London" or "America/New_York", or奥尔森时区标识符,如"Europe/London""America/New_York",或
  • a UTC offset in the form:UTC偏移量的形式为:

    • +/-[hh]:[mm], e.g. "+04:45", or
    • +/-[hh][mm], e.g. "-0530", or
    • +/-[hh], e.g. "+03", or
  • The strings "Z", "UTC", or "GMT"

For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

onError

Optional. 可选。If $dateFromString encounters an error while parsing the given dateString, it outputs the result value of the provided onError expression. 如果$dateFromString在解析给定的dateString时遇到错误,它将输出提供的onError表达式的结果值。This result value can be of any type.该结果值可以是任何类型。

If you do not specify onError, $dateFromString throws an error if it cannot parse dateString.如果未指定onError$dateFromString在无法解析dateString时抛出错误。

onNull

Optional. 可选。If the dateString provided to $dateFromString is null or missing, it outputs the result value of the provided onNullexpression. 如果提供给$dateFromStringdateStringnull或缺失,则输出提供的onNullexpression的结果值。This result value can be of any type.该结果值可以是任何类型。

If you do not specify onNull and dateString is null or missing, then $dateFromString outputs null.如果未指定onNull,并且dateStringnull或缺失,则$dateFromString输出null

Tip提示
See also: 参阅:

Behavior行为

Example示例Results结果
{ $dateFromString: {
    dateString: "2017-02-08T12:10:40.787"
} }
ISODate("2017-02-08T12:10:40.787Z")
{ $dateFromString: {
     dateString: "2017-02-08T12:10:40.787",
     timezone: "America/New_York"
} }
ISODate("2017-02-08T17:10:40.787Z")
{ $dateFromString: {
     dateString: "2017-02-08"
} }
ISODate("2017-02-08T00:00:00Z")
{ $dateFromString: {
     dateString: "06-15-2018",
     format: "%m-%d-%Y"
} }
ISODate("2018-06-15T00:00:00Z")
{ $dateFromString: {
     dateString: "15-06-2018",
     format: "%d-%m-%Y"
} }
ISODate("2018-06-15T00:00:00Z")

Format Specifiers格式说明符

The following format specifiers are available for use in the <formatString>:以下格式说明符可用于<formatString>

Specifiers说明符Description描述Possible Values可能值
%dDay of Month (2 digits, zero padded)月日(2位数字,零填充)01-31
%GYear in ISO 8601 formatISO 8601格式的年份0000-9999
%HHour (2 digits, zero padded, 24-hour clock)小时(2位数字,零填充,24小时时钟)00-23
%LMillisecond (3 digits, zero padded)毫秒(3位数,零填充)000-999
%mMonth (2 digits, zero padded)月份(2位数字,零填充)01-12
%MMinute (2 digits, zero padded)分钟(2位数字,零填充)00-59
%SSecond (2 digits, zero padded)第二位(2位数字,零填充)00-60
%uDay of week number in ISO 8601 format (1-Monday, 7-Sunday)ISO 8601格式的星期日编号(1-星期一,7-星期日)1-7
%VWeek of Year in ISO 8601 formatISO 8601格式的周1-53
%YYear (4 digits, zero padded)年份(4位数字,零填充)0000-9999
%zThe timezone offset from UTC.与UTC的时区偏移。+/-[hh][mm]
%ZThe minutes offset from UTC as a number. 从UTC偏移的分钟数。For example, if the timezone offset (+/-[hhmm]) was +0445, the minutes offset is +285.例如,如果时区偏移量(+/-[hhmm])为+0445,则分钟偏移量为+285 +/-mmm
%%Percent Character as a Literal文字百分比字符%

Examples示例

Converting Dates转换日期

Consider a collection logmessages that contains the following documents with dates.考虑包含以下日期文档的logmessages集合。

{ _id: 1, date: "2017-02-08T12:10:40.787", timezone: "America/New_York", message:  "Step 1: Started" },
{ _id: 2, date: "2017-02-08", timezone: "-05:00", message:  "Step 1: Ended" },
{ _id: 3, message:  " Step 1: Ended " },
{ _id: 4, date: "2017-02-09", timezone: "Europe/London", message: "Step 2: Started"},
{ _id: 5, date: "2017-02-09T03:35:02.055", timezone: "+0530", message: "Step 2: In Progress"}

The following aggregation uses $dateFromString to convert the date value to a date object:以下聚合使用$dateFromStringdate值转换为日期对象:

db.logmessages.aggregate( [ {
   $project: {
      date: {
         $dateFromString: {
            dateString: '$date',
            timezone: 'America/New_York'
         }
      }
   }
} ] )

The above aggregation returns the following documents and converts each date field to the Eastern Time Zone:上述聚合返回以下文档,并将每个date字段转换为东部时区:

{ "_id" : 1, "date" : ISODate("2017-02-08T17:10:40.787Z") }
{ "_id" : 2, "date" : ISODate("2017-02-08T05:00:00Z") }
{ "_id" : 3, "date" : null }
{ "_id" : 4, "date" : ISODate("2017-02-09T05:00:00Z") }
{ "_id" : 5, "date" : ISODate("2017-02-09T08:35:02.055Z") }

The timezone argument can also be provided through a document field instead of a hard coded argument. timezone参数也可以通过文档字段而不是硬编码参数提供。For example:例如:

db.logmessages.aggregate( [ {
   $project: {
      date: {
         $dateFromString: {
            dateString: '$date',
            timezone: '$timezone'
         }
      }
   }
} ] )

The above aggregation returns the following documents and converts each date field to their respective UTC representations.上述聚合返回以下文档,并将每个date字段转换为各自的UTC表示形式。

{ "_id" : 1, "date" : ISODate("2017-02-08T17:10:40.787Z") }
{ "_id" : 2, "date" : ISODate("2017-02-08T05:00:00Z") }
{ "_id" : 3, "date" : null }
{ "_id" : 4, "date" : ISODate("2017-02-09T00:00:00Z") }
{ "_id" : 5, "date" : ISODate("2017-02-08T22:05:02.055Z") }

onError

If your collection contains documents with unparsable date strings, $dateFromString throws an error unless you provide an aggregation expression to the optional onError parameter.如果集合包含具有不可解析日期字符串的文档,$dateFromString将抛出错误,除非您为可选的onError参数提供聚合表达式

For example, given a collection dates with the following documents:例如,给定具有以下文档的集合dates

{ "_id" : 1, "date" : "2017-02-08T12:10:40.787", timezone: "America/New_York" },
{ "_id" : 2, "date" : "20177-02-09T03:35:02.055", timezone: "America/New_York" }

You can use the onError parameter to return the invalid date in its original string form:您可以使用onError参数以原始字符串形式返回无效日期:

db.dates.aggregate( [ {
   $project: {
      date: {
         $dateFromString: {
            dateString: '$date',
            timezone: '$timezone',
            onError: '$date'
         }
      }
   }
} ] )

This returns the following documents:这将返回以下文档:

{ "_id" : 1, "date" : ISODate("2017-02-08T17:10:40.787Z") }
{ "_id" : 2, "date" : "20177-02-09T03:35:02.055" }

onNull

If your collection contains documents with null date strings, $dateFromString returns null unless you provide an aggregation expression to the optional onNull parameter.如果集合包含具有null日期字符串的文档,$dateFromString将返回null,除非为可选的onNull参数提供聚合表达式。

For example, given a collection dates with the following documents:例如,给定具有以下文档的集合dates

{ "_id" : 1, "date" : "2017-02-08T12:10:40.787", timezone: "America/New_York" },
{ "_id" : 2, "date" : null, timezone: "America/New_York" }

You can use the onNull parameter to have $dateFromString return a date representing the unix epoch instead of null:您可以使用onNull参数让$dateFromString返回表示unix纪元的日期,而不是null

db.dates.aggregate( [ {
   $project: {
      date: {
         $dateFromString: {
            dateString: '$date',
            timezone: '$timezone',
            onNull: new Date(0)
         }
      }
   }
} ] )

This returns the following documents:这将返回以下文档:

{ "_id" : 1, "date" : ISODate("2017-02-08T17:10:40.787Z") }
{ "_id" : 2, "date" : ISODate("1970-01-01T00:00:00Z") }
←  $dateFromParts (aggregation)$dateSubtract (aggregation) →