MongoDB聚合运算符:$toDouble
warning:
这篇文章距离上次修改已过418天,其中的内容可能已经有所变动。
$toDouble是MongoDB的聚合操作符,用于将一个表达式转换为双精度浮点数。这个操作符可以在聚合查询中使用,比如在使用$group或$project阶段。
以下是一些使用$toDouble的例子:
- 将字符串转换为双精度浮点数:
db.collection.aggregate([
{
$project: {
doubleValue: {
$toDouble: "123.456"
}
}
}
])在这个例子中,我们将字符串"123.456"转换为双精度浮点数。
- 将整数转换为双精度浮点数:
db.collection.aggregate([
{
$project: {
doubleValue: {
$toDouble: 123
}
}
}
])在这个例子中,我们将整数123转换为双精度浮点数。
- 将非数字字符串转换为双精度浮点数:
db.collection.aggregate([
{
$project: {
doubleValue: {
$toDouble: "abc"
}
}
}
])在这个例子中,我们将非数字字符串"abc"转换为双精度浮点数,结果将为NaN。
- 将日期对象转换为双精度浮点数:
db.collection.aggregate([
{
$project: {
doubleValue: {
$toDouble: new Date()
}
}
}
])在这个例子中,我们将日期对象转换为双精度浮点数,结果将为日期的UNIX时间戳。
- 将布尔值转换为双精度浮点数:
db.collection.aggregate([
{
$project: {
doubleValue: {
$toDouble: true
}
}
}
])在这个例子中,我们将布尔值true转换为双精度浮点数,结果将为1。
- 将null转换为双精度浮点数:
db.collection.aggregate([
{
$project: {
doubleValue: {
$toDouble: null
}
}
}
])在这个例子中,我们将null转换为双精度浮点数,结果将为null。
以上就是一些使用$toDouble操作符的例子,你可以根据实际需求使用这个操作符。
评论已关闭