文档菜单
文档首页
/
MongoDB 手册
/ / /

$toDouble (聚合)

本页内容

  • 定义
  • 行为
  • 示例
$toDouble

将一个值转换为双精度浮点数。如果值不能转换为双精度浮点数,$toDouble 将报错。如果值是 null 或缺失,$toDouble 返回 null。

$toDouble 的语法如下

{
$toDouble: <expression>
}

$toDouble 接受任何有效的表达式.

$toDouble 是以下 $convert 表达式的缩写

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

以下表格列出了可以转换为双精度浮点数的输入类型

输入类型
行为
布尔型
对于 false 返回 0
对于 true 返回 1
双精度浮点数
无操作。返回双精度浮点数。
十进制数

返回十进制值作为双精度浮点数。

十进制值必须在双精度浮点数的最大值和最小值范围内。

您不能将值小于最小双精度值或大于最大双精度值的十进制值进行转换。

整数
返回作为双精度值的int值。
长整型
返回作为双精度值的长整型值。
字符串

返回字符串的数值作为双精度值。

字符串值必须是10进制数值(例如:"-5.5""123456")并且落在双精度的最小值和最大值范围内。

您不能将非10进制数值的字符串(例如:"0x6400")或超出双精度最小值和最大值范围的值进行转换。

日期
返回自纪元以来与日期值对应的毫秒数。

下表列出了一些转换到双精度的示例

示例
结果
$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

本页内容