Definition定义
$toDoubleConverts a value to a double. If the value cannot be converted to an double,将值转换为双精度。如果该值不能转换为double,则$toDoubleerrors. If the value is null or missing,$toDoublereturns null.$toDouble错误。如果该值为null或缺失,$toDouble将返回null。$toDoublehas the following syntax:具有以下语法:{
$toDouble: <expression>
}The$toDoubletakes any valid expression.$toDouble接受任何有效的表达式。The$toDoubleis a shorthand for the following$convertexpression:$toDouble是以下$convert表达式的简写:{ $convert: { input: <expression>, to: "double" } }
Behavior行为
The following table lists the input types that can be converted to a double:下表列出了可以转换为double的输入类型:
0 for false.false返回0。1 for true.true返回1。 | |
| Decimal |
|
double形式返回int值。 | |
double形式返回long值。 | |
| |
| Date |
The following table lists some conversion to double examples:下表列出了一些双重转换示例:
$toDouble: true | 1 |
$toDouble: false | 0 |
$toDouble: 2.5 | 2.5 |
$toDouble: Int32(5) | 5 |
$toDouble: Long(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 }
Note
If the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use 如果转换操作遇到错误,聚合操作将停止并抛出错误。要覆盖此行为,请改用$convert instead.$converter。