MongoDB聚合运算符:$toDate
文章目录
$toDate
聚合运算符将指定的值转换为日期类型,如果无法转换则返回错误,如果指定的值为
null
或引用缺失字段,返回
null
。
语法
{
$toDate: <expression>
}
$toDate
接受任何有效的表达式。
$toDate
是$convert
表达式的简写形式:
{
$convert: {
input: <expression>, to: "date" } }
使用
下表列出了可转换为日期值的类型:
输入类型 | 规则 |
---|---|
Double | 返回与截断双精度值表示的毫秒数相对应的日期,其中正数对应1970年1月1日以来的毫秒数,负数对应1970年1月1日之前的毫秒数。 |
Decimal | 返回与截断双精度值表示的毫秒数相对应的日期,其中正数对应1970年1月1日以来的毫秒数,负数对应1970年1月1日之前的毫秒数。 |
Long | 返回与long值所代表的毫秒数相对应的日期,其中正数对应1970年1月1日以来的毫秒数,负数对应1970年1月1日之前的毫秒数。 |
String | 返回与日期字符串对应的日期,字符串必须是有效的日期,如:"2018-03-20" 、"2018-03-20T12:00:00Z" 、"2018-03-20T12:00:00+0500" |
ObjectId | 返回与 ObjectId 的时间戳对应的日期 |
Timestamp | 返回与时间戳对应的日期 |
下表列出了一些转换为日期值的示例:
示例 | 结果 |
---|---|
{$toDate: 120000000000.5} |
ISODate("1973-10-20T21:20:00Z") |
{$toDate: NumberDecimal("1253372036000.50")} |
ISODate("2009-09-19T14:53:56Z") |
{$toDate: NumberLong("1100000000000")} |
ISODate("2004-11-19T11:33:20Z") |
{$toDate: NumberLong("-1100000000000")} |
ISODate("1935-02-22T12:26:40Z") |
{$toDate: ObjectId("5ab9c3da31c2ab715d421285")} |
ISODate("2018-03-27T04:08:58Z") |
{$toDate: "2018-03-20"} |
ISODate("2018-03-20T00:00:00Z") |
{$toDate: "2018-03-20 11:00:06 +0500"} |
ISO |