“文档” 菜单
文档首页
/
MongoDB Manual
/ / /

$toDate(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$toDate

将数值转换为日期。如果该值无法转换为日期,则 $toDate 出错。如果该值为空或缺失,$toDate 将返回空值。

$toDate 通过以下语法实现:

{
$toDate: <expression>
}

$toDate可采用任何有效的表达式。

$toDate 是以下 $convert 表达式的简写:

{ $convert: { input: <expression>, to: "date" } }

提示

另请参阅:

下表列出了可转换为日期的输入类型:

输入类型
行为
双精度

返回与截断后的由双精度值表示的毫秒数相对应的日期。

正数对应于 1970 年 1 月 1 日以来的毫秒数。

负数对应于 1970 年 1 月 1 日之前的毫秒数。

Decimal 数据类型

返回与由截断后的十进制值表示的毫秒数相对应的日期。

正数对应于 1970 年 1 月 1 日以来的毫秒数。

负数对应于 1970 年 1 月 1 日之前的毫秒数。

返回与该长值表示的毫秒数相对应的日期。

正数对应于 1970 年 1 月 1 日以来的毫秒数。

负数对应于 1970 年 1 月 1 日之前的毫秒数。

字符串

返回与日期字符串相对应的日期。

该字符串必须为有效的日期字符串,例如:

  • "2018-03-20"

  • "2018-03-20T12:00:00Z"

  • "2018-03-20T12:00:00+0500"

ObjectId
返回与对象标识符的时间戳对应的日期。
时间戳
返回与时间戳相对应的日期。

下表列出了转换为日期的部分示例:

例子
结果
{$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"}
ISODate("2018-03-20T06:00:06Z")
{$toDate: "Friday"}
错误
{$toDate: Timestamp({ t: 1637688118, i: 1 })}
ISODate("2021-11-23T17:21:58.00Z")

使用以下文档创建集合 orders

db.orders.insertMany( [
{ _id: 1, item: "apple", qty: 5, price: 2, order_date: new Date( "2018-03-20" ) },
{ _id: 2, item: "pie", qty: 10, price: 3, order_date: new Date( "2018-03-22" ) },
{ _id: 3, item: "ice cream", qty: 2, price: 4, order_date: "2018-03-15" },
{ _id: 4, item: "almonds" , qty: 5, price: 7, order_date: "2018-03-15 +10:00" }
] )

以下针对 orders 集合的聚合操作会将 order_date 转换为日期,然后再按日期值排序:

// Define stage to add convertedDate field with the converted order_date value
dateConversionStage = {
$addFields: {
convertedDate: { $toDate: "$order_date" }
}
};
// Define stage to sort documents by the converted date
sortStage = {
$sort: { "convertedDate": 1 }
};
db.orders.aggregate( [
dateConversionStage,
sortStage
] )

该操作将返回以下文档:

{
_id: 4,
item: 'almonds',
qty: 5,
price: 7,
order_date: '2018-03-15 +10:00',
convertedDate: ISODate("2018-03-14T14:00:00.000Z")
},
{
_id: 3,
item: 'ice cream',
qty: 2,
price: 4,
order_date: '2018-03-15',
convertedDate: ISODate("2018-03-15T00:00:00.000Z")
},
{
_id: 1,
item: 'apple',
qty: 5,
price: 2,
order_date: ISODate("2018-03-20T00:00:00.000Z"),
convertedDate: ISODate("2018-03-20T00:00:00.000Z")
},
{
_id: 2,
item: 'pie',
qty: 10,
price: 3,
order_date: ISODate("2018-03-22T00:00:00.000Z"),
convertedDate: ISODate("2018-03-22T00:00:00.000Z")
}

注意

如果转换操作遇到错误,聚合操作会停止并抛出错误。要覆盖此行为,请改为使用 $convert

← $toBool(聚合)

在此页面上