Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$toDouble(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$toDouble

将值转换为双精度值。如果该值无法转换为双精度值,则 $toDouble出错。如果值为 null 或缺失,则$toDouble返回 null。

$toDouble 通过以下语法实现:

{
$toDouble: <expression>
}

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

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

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

下表列出了可转换为双精度值的输入类型:

输入类型
行为
布尔
返回 0 以表示 false
返回 1 以表示 true
双精度
不操作。返回双进度值。
Decimal 数据类型

以双进度值形式返回该十进制值。

该十进制值必须介于双精度值的最小值与最大值范围之间。

如果某一十进制值的值小于最小双精度值或大于最大双精度值,则无法转换该十进制值。

整型
以双精度值形式返回该 int 值。
长整型
以双精度值形式返回该 long 值。
字符串

以双精度值形式返回该字符串的数值。

该字符串值必须是以 10 为基数的数值(例如 "-5.5""123456"),且介于双精度值的最小值与最大值之间。

无法转换不以 10 为基数的字符串值(例如"0x6400")或超出双精度值最小值和最大值的值。

Date
返回日期值对应的纪元起的毫秒数。

下表列出了转换为双精度值的部分示例:

例子
结果
$toDouble: true
1
$toDouble: false
0
$toDouble: 2.5
2.5
$toDouble: NumberInt(5)
5
$toDouble: NumberLong(10000)
10000
$toDouble: "-5.5"
-5.5
$toDouble: ISODate("2018-03-27T05:04:47.890Z")
1522127087890

使用以下文档创建集合 weather

db.weather.insertMany( [
{ _id: 1, date: new Date("2018-06-01"), temp: "26.1C" },
{ _id: 2, date: new Date("2018-06-02"), temp: "25.1C" },
{ _id: 3, date: new Date("2018-06-03"), temp: "25.4C" },
] )

以下针对 weather 集合的聚合操作会解析 temp 值并将其转换为双精度值:

// Define stage to add degrees field with converted value
tempConversionStage = {
$addFields: {
degrees: { $toDouble: { $substrBytes: [ "$temp", 0, 4 ] } }
}
};
db.weather.aggregate( [
tempConversionStage,
] )

该操作将返回以下文档:

{ "_id" : 1, "date" : ISODate("2018-06-01T00:00:00Z"), "temp" : "26.1C", "degrees" : 26.1 }
{ "_id" : 2, "date" : ISODate("2018-06-02T00:00:00Z"), "temp" : "25.1C", "degrees" : 25.1 }
{ "_id" : 3, "date" : ISODate("2018-06-03T00:00:00Z"), "temp" : "25.4C", "degrees" : 25.4 }

注意

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

← $toDecimal(聚合)

在此页面上