MongoDB聚合运算符:$toDouble

发布于:2024-05-10 ⋅ 阅读:(23) ⋅ 点赞:(0)

MongoDB聚合运算符:$toDouble


$toDouble聚合运算符将指定的值转换为Double类型。如果指定的值为空或缺失,则返回null;如果值无法被转换为Double,则报错。

语法

{
   $toDouble: <expression>
}

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

$toDouble$convert表达式的简写形式:

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

使用

下表列出了可转换为布尔值的类型:

输入类型 规则
Boolean 对于True,返回1,对于False返回0
Decimal 以Double返回Decimal的值,Decimal的值必须在Double的范围内,超出Double值域范围的Decimal不能转换
Double 原样返回
Integer 以Double返回整数值
Long 以Double返回Long值
String 将字符串转换为Double返回,但字符串表示的必须是10进制的比如"-5.5"、“1233”,非10进制的会报错,如:“0x3343”
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值转换为Double:

//将转换后的字段添加到文档

// 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 }

网站公告

今日签到

点亮在社区的每一天
去签到