文档菜单
文档首页
/
MongoDB 手册
/ / /

$convert (聚合查询)

本页内容

  • 定义
  • 兼容性
  • 语法
  • 行为
  • 示例
$convert

将值转换为指定的类型。

您可以使用 $convert 在以下环境中部署

  • MongoDB Atlas:云中MongoDB部署的全托管服务

  • MongoDB Enterprise:基于订阅的自托管MongoDB版本

  • MongoDB Community:源代码可用的、免费使用且自托管的MongoDB版本

已更改在版本8.0.

{
$convert:
{
input: <expression>,
to: <type expression> || {
type: <type expression>,
subtype: <int>
},
format: <string>,
onError: <expression>,
onNull: <expression>
}
}

$convert接受具有以下字段的文档

字段
必需性
描述
input
必需
参数可以是任何有效的表达式。有关表达式更多信息,请参阅表达式运算符。
to
必需

指定将input表达式转换为的类型。您可以将to设置为以下值之一

  • 目标类型的字符串或数字标识符。请参阅to.type

  • 包含to.typeto.subtype字段的对象。使用此格式转换为binData并指定binData子类型。

to.type
如果指定to为对象,则必需

参数可以是任何有效的表达式,该表达式解析为以下数值或字符串标识符之一

字符串标识符
数字标识符
备注
"double"
1
有关转换为双精度浮点数的更多信息,请参阅转换为双精度浮点数。
"string"
2
有关转换为字符串的更多信息,请参阅转换为字符串。
"binData"
5
有关转换为binData的更多信息,请参阅转换为BinData。
"objectId"
7
有关转换为objectId的更多信息,请参阅转换为ObjectId。
"bool"
8
有关转换为布尔值的更多信息,请参阅转换为布尔值。
"date"
9
有关转换为日期的更多信息,请参阅转换为日期。
"int"
16
有关转换为整数的更多信息,请参阅转换为整数。
"long"
18
有关转换为长整型的更多信息,请参阅转换为长整型。
"decimal"
19
有关转换为小数的更多信息,请参阅转换为小数。
to.subtype
可选

如果 to.typebinData,则 to.subtype 指定了要转换成的 binData 子类型。您可以为 to.subtype 指定以下值之一

数字
描述
0
通用二进制子类型
1
函数数据
2
二进制(旧版)
3
UUID(旧版)
4
UUID
5
MD5
6
加密 BSON 值
7

压缩时间序列数据

在版本5.2.

8
敏感数据,例如密钥或秘密。MongoDB 不记录具有子类型 8 的二进制数据的字面值。相反,MongoDB 记录一个占位符值 ###
9
向量数据,它是密集排列的相同类型数字数组。
128
自定义数据

默认值: 0(通用二进制子类型)

格式
在转换到或从 binData 转换时必需。

指定输入或输出的 binData 格式。可以是以下值之一

  • base64

  • base64url

  • utf8

  • hex

  • uuid

如果 formatuuid,则 to.subtype 必须是 4

onError
可选

在转换过程中遇到错误时返回的值,包括不支持的数据类型转换。参数可以是任何有效的 表达式。

如果未指定,则在遇到错误时操作抛出错误并停止。

onNull
可选

如果 input 为 null 或缺失时返回的值。参数可以是任何有效的 表达式。

如果未指定,则在 input 为 null 或缺失时,$convert 返回 null。

除了 $convert 之外,MongoDB 在默认 "onError" 和 "onNull" 行为可接受时提供以下聚合运算符作为缩写

您只能将字符串转换为 binData。所有其他输入类型都将导致错误。

请参阅以下转换为 binData 的示例

示例
结果
{
input: "hn3uUsMxSE6S0cVkebjmfg==",
to: {
type: "binData",
subtype: 0
},
format: "base64"
}
Binary.createFromBase64('hn3uUsMxSE6S0cVkebjmfg==', 0)
{
input: "hn3uUsMxSE6S0cVkebjmfg==",
to: "binData",
format: "base64"
}
Binary.createFromBase64('hn3uUsMxSE6S0cVkebjmfg==', 0)
{
input: "867dee52-c331-484e-92d1-c56479b8e67e",
to: {
type: "binData",
subtype: 0
},
format: "base64",
}
Failed to parse BinData '867dee52-c331-484e-92d1-c56479b8e67e'
in $convert with no onError value: Input is not a valid base64
string.
{
input: "hn3uUsMxSE6S0cVkebjmfg==",
to: {
type: "binData",
subtype: 4
},
format: "base64"
}
Failed to parse BinData 'hn3uUsMxSE6S0cVkebjmfg==' in $convert
with no onError value: Input is not a valid base64 string.
{
input: "867dee52-c331-484e-92d1-c56479b8e67e",
to: {
type: "binData",
subtype: 4
},
format: "uuid"
}
UUID('867dee52-c331-484e-92d1-c56479b8e67e')
{
input: "äöäöä",
to: {
type: "binData",
subtype: 4
},
format: "uuid"
}
Failed to parse BinData 'äöäöä' in $convert with no onError
value: Input is not a valid UUID string.
{
input: "867dee52-c331-484e-92d1-c56479b8e67e",
to: { type: "binData" },
format: "uuid"
}
Failed to parse BinData '867dee52-c331-484e-92d1-c56479b8e67e'
in $convert with no onError value: Only the UUID subtype (4)
is allowed with the 'uuid' format.
{
input: 123,
to: { type: "binData", subtype: 0 }
}
Unsupported conversion from int to binData in $convert with no onError value

以下表格列出了可以转换为布尔值的输入类型

输入类型
行为
数组
返回 true
二进制数据
返回 true
布尔值
无操作。返回布尔值。
代码
返回 true
日期
返回 true
十进制
如果不为零,则返回 true
如果为零,则返回 false
双精度浮点数
如果不为零,则返回 true
如果为零,则返回 false
整数
如果不为零,则返回 true
如果为零,则返回 false
JavaScript
返回 true
长整型
如果不为零,则返回 true
如果为零,则返回 false
MaxKey
返回 true
MinKey
返回 true
空值

返回 onNull 选项指定的值。默认返回 null。

对象
返回 true
ObjectId
返回 true
正则表达式
返回 true
字符串
返回 true
时间戳
返回 true

有关 MongoDB 中数据类型的更多信息,请参阅 BSON 类型。

以下表格列出了一些转换为布尔值的示例

示例
结果
{ input: true, to: "bool" }
true
{ input: false, to: "bool" }
false
{ input: 1.99999, to: "bool" }
true
{ input: Decimal128( "5" ), to: "bool" }
true
{ input: Decimal128( "0" ), to: "bool" }
false
{ input: 100, to: "bool" }
true
{
input: ISODate( "2018-03-26T04:38:28.044Z" ),
to: "bool"
}
true
{ input: "hello", to: "bool" }
true
{ input: "false", to: "bool" }
true
{ input: "", to: "bool" }
true
{ input: null, to: "bool" }
null

提示

另请参阅

以下表格列出了可以转换为整数的输入类型

输入类型
行为
布尔值
对于 false 返回 0
对于 true 返回 1
双精度浮点数

返回截断的值。

截断的双精度浮点值必须位于整数的最大值和最小值之间。

无法将截断值小于最小整数值或大于最大整数值的双精度浮点值转换为整数。

十进制

返回截断的值。

截断的十进制值必须位于整数的最大值和最小值之间。

无法将截断值小于最小整数值或大于最大整数值的十进制值转换为整数。

整数
无操作。返回整数值。
长整型

将长整型值作为整数返回。

长整数值必须在整数的最小值和最大值范围内。

您不能将小于最小整数值或大于最大整数值的长整数值进行转换。

字符串

将字符串的数值作为整数返回。

字符串值必须是一个10进制整数(例如 "-5""123456")并且位于整数的最小值和最大值范围内。

您不能将浮点数、小数或非10进制数字(例如 "-5.0""0x6400")或超出整数最小值和最大值范围的值转换为字符串。

以下表格列出了一些转换为整数的示例

示例
结果
{ input: true, to: "int" }
1
{ input: false, to: "int" }
0
{ input: 1.99999, to: "int" }
1
{ input: Decimal128( "5.5000" ), to: "int" }
5
{
input: Decimal128( "9223372036000.000" ),
to: "int"
}
错误
{ input: Long( "5000" ), to: "int" }
5000
{ input: Long( "922337203600" ), to: "int" }
错误
{ input: "-2", to: "int" }
-2
{ input: "2.5", to: "int" }
错误
{ input: null, to: "int" }
null

提示

另请参阅

$toInt 操作符。

以下表格列出了可以转换为十进制的输入类型

输入类型
行为
布尔值
对于 false 返回 Decimal128( "0" )
对于 true 返回 Decimal128( "1" )
双精度浮点数
将双精度浮点值作为十进制返回。
十进制
无操作。返回十进制。
整数
将整数值作为十进制返回。
长整型
将长整数值作为十进制返回。
字符串

将字符串的数值作为十进制返回。

字符串值必须是一个10进制数值(例如 "-5.5""123456")。

您不能将非10进制数字的字符串值(例如 "0x6400")转换为十进制。

日期
返回自纪元以来的毫秒数,对应于日期值。

以下表格列出了转换为十进制的示例

示例
结果
{ input: true, to: "decimal" }
Decimal128("1")
{ input: false, to: "decimal" }
Decimal128("0")
{ input: 2.5, to: "decimal" }
Decimal128( "2.50000000000000" )
{ input: Int32( 5 ), to: "decimal" }
Decimal128("5")
{ input: Long( 10000 ), to: "decimal" }
Decimal128("10000")
{ input: "-5.5", to: "decimal" }
Decimal128("-5.5")
{
input: ISODate( "2018-03-26T04:38:28.044Z" ),
to: "decimal"
}
Decimal128("1522039108044")

提示

另请参阅

以下表格列出了可以转换为双精度的输入类型

输入类型
行为
布尔值
对于 false 返回 NumberDouble(0)。
对于 true 返回 NumberDouble(1)。
双精度浮点数
无操作。返回双精度浮点数。
十进制

返回十进制值作为双精度浮点数。

十进制值必须介于双精度浮点数的最小值和最大值之间。

您不能将小于最小双精度浮点数或大于最大双精度浮点数的十进制值转换为双精度浮点数。

整数
返回整数值作为双精度浮点数。
长整型
返回长整数值作为双精度浮点数。
字符串

返回字符串的数值作为双精度浮点数。

字符串值必须是10进制数值(例如 "-5.5""123456")并且介于双精度浮点数的最小值和最大值之间。

您不能将非10进制数值(例如 "0x6400")或超出双精度浮点数最小值和最大值的值转换为字符串。

日期
返回自纪元以来的毫秒数,对应于日期值。

以下表格列出了一些转换为双精度浮点数的示例

示例
结果
{ input: true, to: "double" }
1
{ input: false, to: "double" }
0
{ input: 2.5, to: "double" }
2.5
{ input: Int32( 5 ), to: "double" }
5
{ input: Long( "10000" ), to: "double" }
10000
{ input: "-5.5", to: "double" }
-5.5
{ input: "5e10", to: "double" }
50000000000
{
input: ISODate( "2018-03-26T04:38:28.044Z" ),
to: "double"
}
1522039108044

提示

另请参阅

以下表格列出了可以转换为长整型的输入类型

输入类型
行为
布尔值
对于 false 返回 0
对于 true 返回 1
双精度浮点数

返回截断的值。

截断的双精度浮点值必须介于长整型最小值和最大值之间。

您不能将截断值小于最小长整型值或大于最大长整型值的双精度浮点数转换为长整型。

十进制

返回截断的值。

截断的十进制值必须介于长整型最小值和最大值之间。

您不能将截断值小于最小长整型值或大于最大长整型值的十进制值转换为长整型。

整数
将整数值作为长整型返回。
长整型
无操作。返回长整数值。
字符串

返回字符串的数值。

字符串值必须是10进制长整型(例如 "-5""123456")并且介于长整型的最小值和最大值之间。

您不能将浮点数、十进制数、非10进制数(例如 "-5.0""0x6400")或超出长整型最小值和最大值的值转换为字符串。

日期
将日期转换为自纪元以来的毫秒数。

以下表格列出了转换为长整型的示例

示例
结果
{ input: true, to: "long" }
Long("1")
{ input: false, to: "long" }
Long("0")
{ input: 2.5, to: "long" }
Long("2")
{ input: Decimal128( "5.5000" ), to: "long" }
Long("5")
{
input: Decimal128( "9223372036854775808.0" ),
to: "long"
}
错误
{ input: Int32( 8 ), to: "long" }
Long("8")
{
input: ISODate( "2018-03-26T04:38:28.044Z" ),
to: "long"
}
Long("1522039108044")
{ input: "-2", to: "long" }
Long("-2")
{ input: "2.5", to: "long" }
错误
{ input: null, to: "long" }
null

提示

另请参阅

以下表格列出了可以转换为日期的输入类型

输入类型
行为
双精度浮点数

返回与截断双精度值表示的毫秒数相对应的日期。

正数表示自1970年1月1日以来的毫秒数。

负数表示1970年1月1日之前的毫秒数。

十进制

返回与截断十进制值表示的毫秒数相对应的日期。

正数表示自1970年1月1日以来的毫秒数。

负数表示1970年1月1日之前的毫秒数。

长整型

返回与长值表示的毫秒数相对应的日期。

正数表示自1970年1月1日以来的毫秒数。

负数表示1970年1月1日之前的毫秒数。

字符串

返回与日期字符串相对应的日期。

字符串必须是有效的日期字符串,例如

  • "2018-03-03"

  • "2018-03-03T12:00:00Z"

  • "2018-03-03T12:00:00+0500"

ObjectId
返回与ObjectId的时间戳相对应的日期。
时间戳
返回与时间戳相对应的日期。

以下表格列出了一些转换为日期的示例

示例
结果
{
input: 120000000000.5,
to: "date"
}
ISODate("1973-10-20T21:20:00.000Z")
{
input: Decimal128( "1253372036000.50" ),
to: "date"
}
ISODate("2009-09-19T14:53:56.000Z")
{
input: Long( "1100000000000" ),
to: "date
}
ISODate("2004-11-09T11:33:20.000Z")
{
input: Long( "-1100000000000" ),
to: "date"
}
ISODate("1935-02-22T12:26:40.000Z")
{
input: ObjectId( "5ab9c3da31c2ab715d421285" ),
to: "date"
}
ISODate("2018-03-27T04:08:58.000Z")
{ input: "2018-03-03", to: "date" }
ISODate("2018-03-03T00:00:00.000Z")
{
input: "2018-03-20 11:00:06 +0500",
to: "date"
}
ISODate("2018-03-20T06:00:06.000Z")
{ input: "Friday", to: "date" }
错误
{
input: Timestamp( { t: 1637688118, i: 1 } ),
to: "date"
}
ISODate("2021-11-23T17:21:58.000Z")

提示

另请参阅

以下表格列出了可以转换为ObjectId的输入类型

输入类型
行为
字符串

返回长度为24的十六进制字符串的ObjectId。

不能将不是长度为24的十六进制字符串的字符串值转换为ObjectId。

以下表格列出了一些转换为日期的示例

示例
结果
{
input: "5ab9cbfa31c2ab715d42129e",
to: "objectId"
}
ObjectId("5ab9cbfa31c2ab715d42129e")
{
input: "5ab9cbfa31c2ab715d42129",
to: "objectId"
}
错误

提示

另请参阅

$toObjectId 操作符。

以下表格列出了可以转换为字符串的输入类型

输入类型
行为
BinData
返回二进制数据值作为字符串。
布尔值
返回布尔值作为字符串。
双精度浮点数
返回双精度值作为字符串。
十进制
返回十进制值作为字符串。
整数
返回整数值作为字符串。
长整型
返回长整数值作为字符串。
ObjectId
返回ObjectId值作为十六进制字符串。
字符串
无操作。返回字符串值。
日期
返回日期作为字符串。

以下表格列出了一些转换为字符串的示例

示例
结果
{ input: true, to: "string" }
"true"
{ input: false, to: "string" }
"false"
{ input: 2.5, to: "string" }
"2.5"
{ input: Int32( 2 ), to: "string" }
"2"
{ input: Long( 1000 ), to: "string" }
"1000"
{
input: ObjectId( "5ab9c3da31c2ab715d421285" ),
to: "string"
}
"5ab9c3da31c2ab715d421285"
{
input: ISODate( "2018-03-27T16:58:51.538Z" ),
to: "string"
}
"2018-03-27T16:58:51.538Z"
{
input: BinData(4, "hn3f"),
to: "string",
format: "base64"
}
'hn3f'

提示

另请参阅

创建一个包含以下文档的集合 orders

db.orders.insertMany( [
{ _id: 1, item: "apple", qty: 5, price: 10 },
{ _id: 2, item: "pie", qty: 10, price: Decimal128("20.0") },
{ _id: 3, item: "ice cream", qty: 2, price: "4.99" },
{ _id: 4, item: "almonds" },
{ _id: 5, item: "bananas", qty: 5000000000, price: Decimal128("1.25") }
] )

orders 集合上执行以下聚合操作将 price 转换为十进制

// Define stage to add convertedPrice and convertedQty fields with
// the converted price and qty values.
// If price or qty values are missing, the conversion returns a
// value of decimal value or int value of 0.
// If price or qty values cannot be converted, the conversion returns
// a string
priceQtyConversionStage = {
$addFields: {
convertedPrice: { $convert:
{
input: "$price",
to: "decimal",
onError: "Error",
onNull: Decimal128("0")
} },
convertedQty: { $convert:
{
input: "$qty",
to: "int",
onError:{ $concat:
[
"Could not convert ",
{ $toString:"$qty" },
" to type integer."
]
},
onNull: Int32("0")
} },
}
};
totalPriceCalculationStage = {
$project: { totalPrice: {
$switch: {
branches: [
{ case:
{ $eq: [ { $type: "$convertedPrice" }, "string" ] },
then: "NaN"
},
{ case:
{ $eq: [ { $type: "$convertedQty" }, "string" ] },
then: "NaN"
},
],
default: { $multiply: [ "$convertedPrice", "$convertedQty" ] }
}
} } };
db.orders.aggregate( [
priceQtyConversionStage,
totalPriceCalculationStage
])

操作返回以下文档

{ _id: 1, totalPrice: Decimal128("50") },
{ _id: 2, totalPrice: Decimal128("200.0") },
{ _id: 3, totalPrice: Decimal128("9.98") },
{ _id: 4, totalPrice: Decimal128("0") },
{ _id: 5, totalPrice: 'NaN' }

注意

以下示例使用 mongosh。在传统的 mongo shell 中,默认类型不同。

返回

$cond