Database Manual / Reference / Query Language / Expressions

$convert (expression operator)(表达式运算符)

Definition定义

$convert
Converts a value to a specified type.将值转换为指定类型。

Compatibility兼容性

You can use $convert for deployments hosted in the following environments:您可以将$convert用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

Changed in version 8.0.在版本8.0中的更改。

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

The $convert takes a document with the following fields:$convert接受一个包含以下字段的文档:

Field字段Necessity必要性Description描述
inputRequired必需

The argument can be any valid expression. 参数可以是任何有效的表达式For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Starting in MongoDB 8.1, you can set input to binData if you set to to one of the following values:从MongoDB 8.1开始,如果to设置为以下值之一,则可以将input设置为binData

  • int
  • long
  • double

MongoDB also supports these numeric types as input when converting a value to binData.MongoDB在将值转换为binData时也支持这些数字类型作为输入。

toRequired必需

Specifies the type to convert the input expression to. You can set to to one of these values:指定要将input表达式转换为的类型。您可以将设置为以下值之一:

  • A string or numeric identifier for the target type. See to.type.目标类型的字符串或数字标识符。请参见to.type
  • An object containing the fields to.type and to.subtype. Use this format to convert to binData and specify a binData subtype.包含to.typeto.subtype字段的对象。使用此格式转换为binData并指定binData子类型。
to.typeRequired if specifying to as an object如果to指定为对象,则需要

The argument can be any valid expression that resolves to one of the following numeric or string identifiers:参数可以是解析为以下数字或字符串标识符之一的任何有效表达式

String Identifier字符串标识符Numeric Identifier数字标识符Notes备注
"double"1For more information on the conversion to double, see Convert to Double.有关转换为double的详细信息,请参阅转换为double
"string"2For more information on the conversion to string, see Convert to String.有关转换为字符串的详细信息,请参阅转换为字符串
"binData"5For more information on the conversion to binData, see Convert to BinData.有关转换为binData的更多信息,请参阅转换为binData
"objectId"7For more information on the conversion to objectId, see Convert to ObjectId.有关转换为objectId的详细信息,请参阅转换为objectId
"bool"8For more information on the conversion to boolean, see Convert to Boolean.有关转换为布尔值的详细信息,请参阅转换为布尔
"date"9For more information on the conversion to date, see Convert to Date.有关转换为日期的更多信息,请参阅转换为日期
"int"16For more information on the conversion to integer, see Convert to Integer.有关转换为整数的详细信息,请参阅转换为整数
"long"18For more information on the conversion to long, see Convert to Long.有关转换为long的详细信息,请参阅转换为long
"decimal"19For more information on the conversion to decimal, see Convert to Decimal.有关转换为十进制的详细信息,请参阅转换为十进制
to.subtypeOptional可选

If to.type is binData, to.subtype specifies the binData subtype to convert to. You can specify one of these values for to.subtype:如果to.typebinDatato.subtype会指定要转换为的binData子类型。您可以为to.subtype指定以下值之一:

Number数字Description描述
0Generic binary subtype通用二进制子类型
1Function data函数数据
2Binary (old)
3UUID (old)
4UUID
5MD5
6Encrypted BSON value加密的BSON值
7

Compressed time series data压缩时间序列数据

New in version 5.2.在版本5.2中新增。

8Sensitive data, such as a key or secret. MongoDB does not log literal values for binary data with subtype 8. Instead, MongoDB logs a placeholder value of ###.敏感数据,如键或秘密。MongoDB不会记录子类型为8的二进制数据的文字值。相反,MongoDB会记录一个占位符值###
9Vector data, which is densely packed arrays of numbers of the same type.矢量数据,它是由同一类型的数字组成的密集数组。
128Custom data自定义数据

Default: 0 (Generic binary subtype)默认值:0(通用二进制子类型)

byteOrderOptional可选Specifies big or little endian byte ordering for conversions between binData and numeric types. If unspecified, the default is little endian byte ordering.指定binData和数值类型之间转换的大端字节序或小端字节序。如果未指定,则默认为小字节序。
formatRequired when converting to or from binData and string在与binData和字符串进行转换时需要

Specifies format of conversions between binData and string指定binData和字符串之间的转换格式

  • base64
  • base64url
  • utf8
  • hex
  • uuid

If format is uuid, to.subtype must be 4.如果formatuuid,则to.subtype必须为4

onErrorOptional可选

Value to return on encountering an error during conversion, including unsupported type conversions. The arguments can be any valid expression.在转换过程中遇到错误时返回的值,包括不支持的类型转换。参数可以是任何有效的表达式

If unspecified, the operation throws an error upon encountering an error and stops.如果未指定,则操作在遇到错误时抛出错误并停止。

onNullOptional可选

Value to return if the input is null or missing. The arguments can be any valid expression.如果输入为null或缺失,则返回值。参数可以是任何有效的表达式

If unspecified, $convert returns null if the input is null or missing.如果未指定,如果inputnull或缺失,则$convert将返回null

In addition to $convert, MongoDB provides the following aggregation operators as shorthand when the default "onError" and "onNull" behavior is acceptable:除了$convert之外,当默认的“onError”和“onNull”行为可接受时,MongoDB还提供以下聚合运算符作为简写:

Behavior行为

Convert to BinData转换为BinData

Starting in MongoDB 8.1, you can set input to binData if you set to to one of the following values:从MongoDB 8.1开始,如果to设置为以下值之一,则可以将input设置为binData

  • int
  • long
  • double

Starting in MongoDB 8.1, $convert returns an error when attempting to convert between different binData subtypes. In MongoDB 8.0, $convert returns the original value and original subtype: no conversion is performed. MongoDB versions before 8.0 don't have binData conversion.从MongoDB 8.1开始,$convert在尝试在不同binData子类型之间转换时返回错误。在MongoDB 8.0中,$convert返回原始值和原始子类型:不执行转换。8.0之前的MongoDB版本没有binData转换。

Convert from numeric types to binData:从数值类型转换为binData

When converting a numeric type to binData:将数值类型转换为binData时:

  • An int becomes a 4-byte binData.一个int变成一个4字节的binData
  • A long becomes an 8-byte binData.long变为8字节的binData
  • A double becomes an 8-byte binData.double变成8字节的binData

The byteOrder of the numeric output defaults to "little", or the placement of the least significant byte first. In contrast, "big" places the most significant byte first.数字输出的byteOrder默认为“little”,即将最低有效字节放在第一位。相比之下,“big”将最重要的字节放在第一位。

Convert long to binData:long转换为binData

db.t.insertOne({a: Long(42)})

db.t.aggregate([
{
$project: {
convertedBD: {
$convert: {
input: Long(42),
to: "binData",
}
},
}
}
])
{
_id: ObjectId('67dda0195a99e592590143e8'),
convertedBD: Binary.createFromBase64('KgAAAAAAAAA=', 0)
}

Convert long to binData with big-endian byte ordering:使用大端字节顺序将long转换为binData

db.t.insertOne({a: Long(42)})

db.t.aggregate([
{
$project: {
convertedBD: {
$convert: {
input: Long(42),
to: "binData",
byteOrder: "big",
}
},
}
}
])
{
_id: ObjectId('67ddb27c5a99e592590143ec'),
convertedBD: Binary.createFromBase64('AAAAAAAAACo=', 0),
}

Convert double to binData:double转换为binData

db.t.insertOne({a: Double(42.0)})

db.t.aggregate([
{
$project: {
convertedBD: {
$convert: {
input: Double(42),
to: "binData",
}
},
}
}
])
{
_id: ObjectId('67ddb3cf5a99e592590143ee'),
convertedBD: Binary.createFromBase64('AAAAAAAARUA=', 0)
}

Convert int to binData:

db.t.insertOne({a: 42})

db.t.aggregate([
{
$project: {
convertedBD: {
$convert: {
input: 42,
to: "binData",
}
},
}
}
])
{
_id: ObjectId('67ddb43a5a99e592590143ef'),
convertedBD: Binary.createFromBase64('KgAAAA==', 0)
}

Convert from string to BinData从字符串转换为BinData

MongoDB also supports conversions between binData and strings.MongoDB还支持binData和字符串之间的转换。

The following examples demonstrate how to convert strings to binData.以下示例演示了如何将字符串转换为binData。

Example示例Result
{
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.

Note

Starting in MongoDB 8.1, $convert returns an error when attempting to convert between different binData subtypes. In MongoDB 8.0, $convert returns the original value and original subtype: no conversion is performed. MongoDB versions before 8.0 don't have binData conversion.从MongoDB 8.1开始,$convert在尝试在不同binData子类型之间转换时返回错误。在MongoDB 8.0中,$convert返回原始值和原始子类型:不执行转换。8.0之前的MongoDB版本没有binData转换。

Convert to Boolean转换为布尔值

The following table lists the input types that can be converted to a boolean:下表列出了可以转换为布尔值的输入类型:

Input Type输入类型Behavior行为
Array数组Returns true返回true
Binary dataReturns true返回true
Boolean布尔值No-op. Returns the boolean value.否。返回布尔值。
CodeReturns true返回true
DateReturns true返回true
DecimalReturns true if not zero如果不为零,则返回true
Return false if zero如果为零,则返回false
Double双精度浮点数Returns true if not zero如果不为零,则返回true
Return false if zero如果为零,则返回false
Integer整数Returns true if not zero如果不为零,则返回true
Return false if zero如果为零,则返回false
JavaScriptReturns true返回true
Long长整数Returns true if not zero如果不为零,则返回true
Return false if zero如果为零,则返回false
MaxKeyReturns true返回true
MinKeyReturns true返回true
NullReturns the value specified for the onNull option. By default, returns null.返回为onNull选项指定的值。默认情况下,返回null
ObjectReturns true返回true
ObjectIdReturns true返回true
Regular expression正则表达式Returns true返回true
String字符串Returns true返回true
Timestamp时间戳Returns true返回true

To learn more about data types in MongoDB, see BSON Types.要了解有关MongoDB中数据类型的更多信息,请参阅BSON类型

The following table lists some conversion to boolean examples:下表列出了一些转换为布尔值的示例:

Example示例Results结果
{ 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

Tip

$toBool

Convert to Integer转换为Integer

The following table lists the input types that can be converted to an integer:下表列出了可以转换为整数的输入类型:

Input Type输入类型Behavior行为
Boolean布尔值Returns 0 for false.返回0表示false
Returns 1 for true.true返回1
BinData

Returns the binData value as an integer. binData is interpreted as two's signed complement signed integer.以整数形式返回binData值。binData被解释为2的带符号补码带符号整数。

The number of bytes in the binData value must be 1, 2, or 4.binData值中的字节数必须为124

If the input is of an unexpected length an error is generated. You can control this behavior by configuring $convert.onError.如果input的长度超出预期,则会生成错误。您可以通过配置$convertonError来控制此行为。

Double双精度浮点数

Returns truncated value.返回截断值。

The truncated double value must fall within the minimum and maximum value for an integer.截断的双精度值必须落在整数的最小值和最大值之间。

You cannot convert a double value whose truncated value is less than the minimum integer value or is greater than the maximum integer value.您无法转换截断值小于最小整数值或大于最大整数值的双精度值。

Decimal

Returns truncated value.返回截断值。

The truncated decimal value must fall within the minimum and maximum value for an integer.截断的十进制值必须落在整数的最小值和最大值之间。

You cannot convert a decimal value whose truncated value is less than the minimum integer value or is greater than the maximum integer value.截断值小于最小整数值或大于最大整数值的十进制值无法转换。

Integer整数No-op. Returns the integer value.否。返回整数值。
Long长整数

Returns the long value as an integer.以整数形式返回长值。

The long value must fall within the minimum and maximum value for an integer.长值必须落在整数的最小值和最大值之间。

You cannot convert a long value that is less than the minimum integer value or is greater than the maximum integer value.您无法转换小于最小整数值或大于最大整数值的长值。

String字符串

Returns the numerical value of the string as an integer.以整数形式返回字符串的数值。

The string value must be a base 10 integer (e.g. "-5", "123456") and fall within the minimum and maximum value for an integer.字符串值必须是以10为底的整数(例如"-5""123456"),并且在整数的最小值和最大值范围内。

You cannot convert a string value of a float or decimal or non-base 10 number (e.g. "-5.0", "0x6400") or a value that falls outside the minimum and maximum value for an integer.您不能转换浮点数、十进制数或非十进制数(例如"-5.0""0x6400")的字符串值,也不能转换整数的最小值和最大值之外的值。

The following table lists some conversion to integer examples:下表列出了一些转换为整数的示例:

Example示例Results结果
{ 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"
}
Error
{ input: Long( "5000" ), to: "int" }
5000
{ input: Long( "922337203600" ), to: "int" }
Error
{ input: "-2", to: "int" }
-2
{ input: "2.5", to: "int" }
Error
{ input: null, to: "int" }
null
{
input: Binary(Buffer.from("00100000", "hex"), 0),
to: "int",
byteOrder: "big",
}
1048576
{
input: Binary(Buffer.from("FFFFE796", "hex"), 0),
to: "int",
}
-1763180545
{
input: Binary(Buffer.from("001000000000000", "hex"), 0),
to: "int",
byteOrder: "big",
}
Error: Failed to convert BinData because of invalid length: 7错误:由于长度无效,无法转换BinData:7

Tip

$toInt operator.运算符

Convert to Decimal转换为Decimal

The following table lists the input types that can be converted to a decimal:下表列出了可以转换为十进制的输入类型:

Input Type输入类型Behavior行为
Boolean布尔值Returns Decimal128( "0" ) for false.false返回Decimal128( "0" )
Returns Decimal128( "1" ) for true.true返回Decimal128( "1" )
Double双精度浮点数Returns double value as a decimal.以十进制形式返回双精度值。
DecimalNo-op. Returns the decimal.否。返回小数。
Integer整数Returns the int value as a decimal.以十进制形式返回int值。
Long长整数Returns the long value as a decimal.以小数形式返回长值。
String字符串

Returns the numerical value of the string as a decimal.以十进制形式返回字符串的数值。

The string value must be of a base 10 numeric value (e.g. "-5.5", "123456").字符串值必须是以10为底的数值(例如"-5.5""123456")的字符串值。

You cannot convert a string value of a non-base 10 number (e.g. "0x6400")您无法转换非十进制数字的字符串值(例如"0x6400"

DateReturns the number of milliseconds since the epoch that corresponds to the date value.返回自与日期值对应的历元以来的毫秒数。

The following table lists some conversion to decimal examples:下表列出了一些转换为十进制的示例:

Example示例Results结果
{ 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")

Convert to Double转换为双精度值

The following table lists the input types that can be converted to a double:下表列出了可以转换为double的输入类型:

Input Type输入类型Behavior
Boolean布尔值Returns NumberDouble(0) for false.false返回NumberDouble(0)
Returns NumberDouble(1) for true.true返回NumberDouble(1)
BinData

Returns the binData value as a double. binData is interpreted as an IEEE 754 single-precision or double-precision floating point.double形式返回binData值。binData被解释为IEEE 754单精度或双精度浮点。

The number of bytes in the binData value must be 4 or 8.binData值中的字节数必须为48

If the input is of an unexpected length an error is generated. You can control this behavior by configuring $convert.onError.如果input的长度超出预期,则会生成错误。您可以通过配置$convert.onError来控制此行为。

Double双精度浮点数No-op. Returns the double.否。返回双倍值。
Decimal

Returns the decimal value as a double.以双精度函数的形式返回十进制值。

The decimal value must fall within the minimum and maximum value for a double.小数值必须落在双精度的最小值和最大值之间。

You cannot convert a decimal value whose value is less than the minimum double value or is greater than the maximum double value.不能转换值小于最小双精度值或大于最大双精度值的十进制值。

Integer整数Returns the int value as a double.以double形式返回int值。
Long长整数Returns the long value as a double.将long值作为double返回。
String字符串

Returns the numerical value of the string as a double.以double形式返回字符串的数值。

The string value must be of a base 10 numeric value (e.g. "-5.5", "123456") and fall within the minimum and maximum value for a double.字符串值必须是以10为底的数值(例如"-5.5""123456")的字符串值,并且在双精度的最小值和最大值范围内。

You cannot convert a string value of a non-base 10 number (e.g. "0x6400") or a value that falls outside the minimum and maximum value for a double.您无法转换非十进制数字的字符串值(例如"0x6400")或超出双精度最小值和最大值的值。

DateReturns the number of milliseconds since the epoch that corresponds to the date value.返回自与日期值对应的历元以来的毫秒数。

The following table lists some conversion to double examples:下表列出了一些双重转换示例:

Example示例Results结果
{ 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
{
input: Binary(Buffer.from("04CCCCCD", "hex"), 0),
to: "double",
byteOrder: "big",
}
4.814824932714571e-36
{
input: Binary(Buffer.from("0000", "hex"), 0),
to: "double",
byteOrder: "big",
}
Error: Failed to convert binData because of invalid length: 2错误:由于长度2无效,无法转换binData

Convert to Long转换为Long

The following table lists the input types that can be converted to a long:下表列出了可以转换为long的输入类型:

Input Type输入类型Behavior行为
Boolean布尔值Returns 0 for false.false返回0
Returns 1 for true.true返回0
BinData

Returns the binData value as a long. binData is interpreted as two's signed complement signed integer.long形式返回binData值。binData被解释为2的带符号补码带符号整数。

The number of bytes in the binData value must be 1, 2, 4 or 8.binData值中的字节数必须为1248

If the input is of an unexpected length an error is generated. You can control this behavior by configuring $convert.onError.如果input的长度超出预期,则会生成错误。您可以通过配置$convert.onError来控制此行为。

Double双精度浮点数

Returns truncated value.返回截断值。

The truncated double value must fall within the minimum and maximum value for a long.截断的双精度值必须在长时间内落在最小值和最大值之间。

You cannot convert a double value whose truncated value is less than the minimum long value or is greater than the maximum long value.您无法转换截断值小于最小长值或大于最大长值的双精度值。

Decimal

Returns truncated value.返回截断值。

The truncated decimal value must fall within the minimum and maximum value for a long.截断的十进制值必须长时间处于最小值和最大值之间。

You cannot convert a decimal value whose truncated value is less than the minimum long value or is greater than the maximum long value.截断值小于最小长值或大于最大长值的十进制值无法转换。

Integer整数Returns the int value as a long.将int值作为long返回。
Long长整数No-op. Returns the long value.无操作,返回long值。
String字符串

Returns the numerical value of the string.返回字符串的数值。

The string value must be of a base 10 long (e.g. "-5", "123456") and fall within the minimum and maximum value for a long.字符串值必须是以10为底的长整型(例如"-5""123456")的字符串值,并且在一个long的最小值和最大值范围内。

You cannot convert a string value of a float or decimal or non-base 10 number (e.g. "-5.0", "0x6400") or a value that falls outside the minimum and maximum value for a long.您不能转换浮点数、十进制数或非十进制数(例如"-5.0""0x6400")的字符串值,也不能转换长时间不在最小值和最大值范围内的值。

DateConverts the Date into the number of milliseconds since the epoch.将日期转换为自纪元以来的毫秒数。

The following table lists some conversion to long examples:下表列出了一些转换为长示例:

Example示例Results结果
{ 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"
}
Error
{ 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" }
Error
{ input: null, to: "long" }
null
{
input: Binary(Buffer.from("001000000", "hex"), 0),
to: "long",
byteOrder: "big",
}
Long("1048576")

Tip

$toLong

Convert to 转换为Date

The following table lists the input types that can be converted to a date:下表列出了可以转换为日期的输入类型:

Input Type输入类型Behavior行为
Double双精度浮点数

Returns a date that corresponds to the number of milliseconds represented by the truncated double value.返回一个日期,该日期对应于截断的双精度值所表示的毫秒数。

Positive number corresponds to the number of milliseconds since Jan 1, 1970.正数对应自1970年1月1日以来的毫秒数。

Negative number corresponds to the number of milliseconds before Jan 1, 1970.负数对应于1970年1月1日之前的毫秒数。

Decimal

Returns a date that corresponds to the number of milliseconds represented by the truncated decimal value.返回与截断的十进制值表示的毫秒数对应的日期。

Positive number corresponds to the number of milliseconds since Jan 1, 1970.正数对应自1970年1月1日以来的毫秒数。

Negative number corresponds to the number of milliseconds before Jan 1, 1970.负数对应于1970年1月1日之前的毫秒数。

Long长整数

Returns a date that corresponds to the number of milliseconds represented by the long value.返回与long值表示的毫秒数对应的日期。

Positive number corresponds to the number of milliseconds since Jan 1, 1970.正数对应自1970年1月1日以来的毫秒数。

Negative number corresponds to the number of milliseconds before Jan 1, 1970.负数对应于1970年1月1日之前的毫秒数。

String字符串

Returns a date that corresponds to the date string.返回与日期字符串对应的日期。

The string must be a valid date string, such as:字符串必须是有效的日期字符串,例如:

  • "2018-03-03"
  • "2018-03-03T12:00:00Z"
  • "2018-03-03T12:00:00+0500"
ObjectIdReturns a date that corresponds to the timestamp of the ObjectId.返回与ObjectId的时间戳对应的日期。
TimestampReturns a date that corresponds to the timestamp.返回与时间戳对应的日期。

The following table lists some conversion to date examples:下表列出了一些迄今为止的转换示例:

Example示例Results结果
{
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" }
Error
{
input: Timestamp( { t: 1637688118, i: 1 } ),
to: "date"
}
ISODate("2021-11-23T17:21:58.000Z")

Tip

Convert to ObjectId转换为ObjectId

The following table lists the input types that can be converted to an ObjectId:下表列出了可以转换为ObjectId的输入类型:

Input Type输入类型Behavior行为
String字符串

Returns an ObjectId for the hexadecimal string of length 24.返回长度为24的十六进制字符串的ObjectId。

You cannot convert a string value that is not a hexadecimal string of length 24.您无法转换长度不是24的十六进制字符串的字符串值。

The following table lists some conversion to date examples:下表列出了一些迄今为止的转换示例:

Example示例Results结果
{
input: "5ab9cbfa31c2ab715d42129e",
to: "objectId"
}
ObjectId("5ab9cbfa31c2ab715d42129e")
{
input: "5ab9cbfa31c2ab715d42129",
to: "objectId"
}
Error

Tip

$toObjectId operator.运算符

Convert to String转换为String

The following table lists the input types that can be converted to a string:下表列出了可以转换为字符串的输入类型:

Input Type输入类型Behavior行为
BinDataReturns the binary data value as a string.以字符串形式返回二进制数据值。
Boolean布尔值Returns the boolean value as a string.以字符串形式返回布尔值。
Double双精度浮点数Returns the double value as a string.以字符串形式返回双精度值。
DecimalReturns the decimal value as a string.以字符串形式返回十进制值。
Integer整数Returns the integer value as a string.以字符串形式返回整数值。
Long长整数Returns the long value as a string.以字符串形式返回长值。
ObjectIdReturns the ObjectId value as a hexadecimal string.以十六进制字符串形式返回ObjectId值。
String字符串No-op. Returns the string value.无操作。返回字符串值。
DateReturns the date as a string.以字符串形式返回日期。

The following table lists some conversion to string examples:下表列出了一些转换为字符串的示例:

Example示例Results结果
{ 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'

Tip

Example示例

Create a collection orders with the following documents:使用以下文档创建集合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") }
] )

The following aggregation operation on the orders collection converts the price to a decimal: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.如果缺少价格或数量值,转换将返回十进制值或0的int值。
// 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
])

The operation returns the following documents:该操作返回以下文档:

{ _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' }

Note

These examples use mongosh. The default types are different in the legacy mongo shell.这些例子使用mongosh。传统mongo shell中的默认类型不同。