$toDouble(aggregation)
On this page本页内容
Definition定义
$toDouble
-
Converts a value to a double.将值转换为双精度。If the value cannot be converted to an double,如果该值无法转换为double,则$toDouble
errors.$toDouble
将出错。If the value is null or missing,如果该值为$toDouble
returns null.null
或缺失,$toDouble
将返回null
。$toDouble
has the following syntax:具有以下语法:{
$toDouble: <expression>
}The$toDouble
takes any valid expression.$toDouble
接受任何有效的表达式。The$toDouble
is a shorthand for the following$convert
expression:$toDouble
是以下$convert
表达式的简写:{ $convert: { input: <expression>, to: "double" } }
Behavior行为
The following table lists the input types that can be converted to a double:下表列出了可以转换为双精度的输入类型:
Boolean | 0 for false .false ,则返回0 。1 for true .true ,则返回1 。 |
Double | |
Decimal | |
Integer | |
Long | |
String | "-5.5" , "123456" ) and fall within the minimum and maximum value for a double."-5.5" 、"123456" ),并且在双精度的最小值和最大值之间。"0x6400" ) or a value that falls outside the minimum and maximum value for a double. |
Date |
The following table lists some conversion to double examples:下表列出了一些转换为双重示例:
$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 |
Example实例
Create a collection 使用以下文档创建集合weather
with the following documents: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" },
] )
The following aggregation operation on the 以下对weather
collection parses the temp
value and converts to a double:weather
集合的聚合操作解析temp
值并将其转换为double
值:
// Define stage to add degrees field with converted value
tempConversionStage = {
$addFields: {
degrees: { $toDouble: { $substrBytes: [ "$temp", 0, 4 ] } }
}
};
db.weather.aggregate( [
tempConversionStage,
] )
The operation returns the following documents:该操作返回以下文档:
{ "_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 }