On this page
$dateFromString (aggregation)
在本页面
Definition
$dateFromString
- 3.6 版的新功能。
将日期/时间字符串转换为日期对象。
$dateFromString表达式具有以下语法:
{ $dateFromString: {
'dateString': <dateStringExpression>,
'timezone': <tzExpression>
}
}
$dateFromString
接收具有以下字段的文档:
Field | Description |
---|---|
dateString |
要转换为日期对象的日期/时间字符串。有关日期/时间格式的更多信息,请参见Date。 |
Note
如果为操作员指定timezone
选项,则不要在dateString
中包括时区信息。
|
| timezone
|可选。用于格式化日期的时区。
> [!NOTE|label:Note]
如果dateString
参数的格式类似于'2017-02-08T12:10:40.787Z',其中末尾的'Z'表示祖鲁时间(UTC 时区),则不能指定timezone
参数。<timezone>
允许使用以下选项和表达式对其求值:
奥尔森时区标识符(例如"Europe/London"
或"America/New_York"
),或
UTC 偏移量,格式为:+/-[hh]:[mm]
,例如"+04:45"
,或+/-[hh][mm]
,例如"-0530"
,或+/-[hh]
,例如"+03"
,或
字符串“ Z”,“ UTC”或“ GMT”
有关表达式的更多信息,请参见Expressions。
如果dateStringExpression
或tzExpression
评估为 null,缺少或未定义,则$ dateFromString 表达式的结果为 null。
Example
考虑一个包含以下文档的集合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"}
以下聚合使用$ dateFromString 将date
值转换为日期对象:
db.logmessages.aggregate( [ {
$project: {
date: {
$dateFromString: {
dateString: '$date',
timezone: 'America/New_York'
}
}
}
} ] )
上述汇总返回以下文档,并将每个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") }
timezone
参数也可以通过文档字段而不是硬编码参数来提供。例如:
db.logmessages.aggregate( [ {
$project: {
date: {
$dateFromString: {
dateString: '$date',
timezone: '$timezone'
}
}
}
} ] )
上面的汇总返回以下文档,并将每个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") }