On this page本页内容
$toDouble
New in version 4.0.在版本4.0中新增。
Converts a value to a double. 将值转换为double。If the value cannot be converted to an double, 如果无法将值转换为$toDouble errors. double,则$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" } }
The following table lists the input types that can be converted to a double:下表列出了可以转换为双精度类型的输入类型:
| Boolean |
|
| Double | |
| Decimal |
|
| Integer | double形式返回int值。 |
| Long | double形式返回长值。 |
| String |
|
| 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 |
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 }