$convert (aggregation)

On this page本页内容

Definition定义

$convert

New in version 4.0.版本4.0中的新功能。

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

$convert has the following syntax:语法如下所示:

{
   $convert:
      {
         input: <expression>,
         to: <type expression>,
         onError: <expression>,  // Optional.
         onNull: <expression>    // Optional.
      }
}

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

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

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

String IdentifierNumeric IdentifierNotes备注
“double” 1 For more information on the conversion to double, see Converting to a Double.有关转换为双精度的详细信息,请参阅转换为双精度
“string” 2 For more information on the conversion to string, see Converting to a String.有关转换为字符串的详细信息,请参阅转换为字符串
“objectId” 7 For more information on the conversion to objectId, see Converting to an ObjectId.有关转换为objectId的更多信息,请参阅转换为objectId
“bool” 8 For more information on the conversion to boolean, see Converting to a Boolean.有关转换为布尔值的详细信息,请参阅转换为布尔值
“date” 9 For more information on the conversion to date, see Converting to a Date.有关转换为日期的详细信息,请参阅转换为日期
“int” 16 For more information on the conversion to integer, see Converting to an Integer.有关转换为整数的详细信息,请参阅转换为整数
“long” 18 For more information on the conversion to long, see Converting to a Long.有关转换为long的详细信息,请参阅转换为long
“decimal” 19 For more information on the conversion to decimal, see Converting to a Decimal.有关转换为十进制的详细信息,请参阅转换为十进制
onError

Optional.可选。The 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.如果未指定,则操作在遇到错误时抛出错误并停止。

onNull

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

If unspecified, $convert returns null if the input is null or missing.如果未指定,$convertinputnull或缺失时返回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行为

Converting to a Boolean转换为布尔值

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

Input Type输入类型Behavior行为
Boolean No-op. Returns the boolean value.不操作。返回布尔值。
Double
Returns true if not zero.如果不是零,则返回true
Return false if zero.如果为零,则返回false
Decimal
Returns true if not zero.如果不是零,则返回true
Return false if zero.如果为零,则返回false
Integer
Returns true if not zero.如果不是零,则返回true
Return false if zero.如果为零,则返回false
Long
Returns true if not zero.如果不是零,则返回true
Return false if zero.如果为零,则返回false
ObjectId
Returns true.返回true
String
Returns true.返回true
Date
Returns true.返回true

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: NumberDecimal("5"), to: "bool"}
true
{ input: NumberDecimal("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

See also参阅

$toBool

Converting to an Integer转换为整数

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

Input Type输入类型Behavior行为
Boolean
Returns 0 for false.false返回0
Returns 1 for true.true返回1
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.long值必须在整数的最小值和最大值之间。

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 base10 integer (e.g. "-5", "123456") and fall within the minimum and maximum value for an integer.字符串值必须是base10整数(例如"-5""123456"),并且在整数的最小值和最大值之间。

You cannot convert a string value of a float or decimal or non-base10 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: NumberDecimal("5.5000"), to: "int"}
5
{ input: NumberDecimal("9223372036000.000"), to: "int"}
Error
{
   input: NumberDecimal("9223372036000.000"),
   to: "int",
   onError: "Could not convert to type integer."
}
“Could not convert to type integer.”“无法转换为整型。”
{ input: NumberLong("5000"), to: "int"}
5000
{ input: NumberLong("922337203600"), to: "int"}
Error
{ input: "-2", to: "int" }
-2
{ input: "2.5", to: "int" }
Error
{ input: null, to: "int" }
null

See also参阅

$toInt operator.操作人员

Converting to a Decimal转换成十进制

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

Input Type输入类型Behavior行为
Boolean
Returns NumberDecimal("0") for false.false返回NumberDecimal("0")
Returns NumberDecimal("1") for true.true返回NumberDecimal("1")
Double Returns double value as a decimal.以十进制形式返回双精度值。
Decimal No-op. Returns the decimal.不操作。返回十进制数。
Integer Returns the int value as a decimal.以十进制形式返回整数值。
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 base10 numeric value (e.g. "-5.5", "123456").字符串值必须是base10数值(例如"-5.5""123456")。

You cannot convert a string value of a non-base10 number (e.g. "0x6400")不能转换非base10数字(例如"0x6400")的字符串值

Date Returns 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"}
NumberDecimal(“1”)
{ input: false, to: "decimal" }
NumberDecimal(“0”)
{ input: 2.5, to: "decimal" }
NumberDecimal(“2.50000000000000”)
{ input: NumberInt(5), to: "decimal"}
NumberDecimal(“5”)
{ input: NumberLong(10000), to: "decimal"}
NumberDecimal(“10000”)
{ input: "-5.5", to: "decimal" }
NumberDecimal(“-5.5”)
{ input: ISODate("2018-03-27T05:04:47.890Z"), to: "decimal" }
NumberDecimal(“1522127087890”)

See also参阅

$toDecimal

Converting to a Double转换成Double

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

Input Type输入类型Behavior行为
Boolean
Returns NumberLong(0) for false.false返回NumberLong(0)
Returns NumberLong(1) for true.true返回NumberLong(1)
Double No-op. Returns the double.不操作。返回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.以双精度形式返回int值。
Long Returns the long value as a double.以双精度形式返回长值。
String

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

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

You cannot convert a string value of a non-base10 number (e.g. "0x6400") or a value that falls outside the minimum and maximum value for a double.不能转换非base10数字(例如"0x6400")的字符串值,也不能转换超出双精度的最小值和最大值的值。

Date Returns 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: NumberInt(5), to: "double"}
5
{ input: NumberLong(10000), to: "double"}
10000
{ input: "-5.5", to: "double" }
-5.5
{ input: "5e10", to: "double" }
50000000000
{
   input: "5e550",
   to: "double",
   onError: "Could not convert to type double."
}
“Could not convert to type double.”
{ input: ISODate("2018-03-27T05:04:47.890Z"), to: "double" }
1522127087890

See also参阅

$toDouble

Converting to a 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返回1
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.以long形式返回int值。
Long No-op. Returns the long value.不操作。返回long值。
String

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

The string value must be of a base10 long (e.g. "-5", "123456") and fall within the minimum and maximum value for a long.字符串值的长度必须为base10(例如"-5""123456"),并且在很长一段时间内都在最小值和最大值之间。

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

Date Converts 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" }
NumberLong(“1”)
{ input: false, to: "long"  }
NumberLong(“0”)
{ input: 1.99999, to: "long"  }
NumberLong(“1”)
{ input: NumberDecimal("5.5000"), to: "long" }
NumberLong(“5”)
{ input: NumberDecimal("9223372036854775808.0"), to: "long" }
Error
{
   input: NumberDecimal("9223372036854775808.000"),
   to: "long",
   onError: "Could not convert to type long."
}
“Could not convert to type long.”
{ input: NumberInt(8), to: "long" }
NumberLong(8)
{ input: ISODate("2018-03-26T04:38:28.044Z"), to: "long" }
NumberLong(“1522039108044”)
{ input: "-2", to: "long" }
NumberLong(“-2”)
{ input: "2.5", to: "long" }
Error
{ input: null, to: "long" }
null

See also参阅

$toLong

Converting to a 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”
ObjectId Returns a date that corresponds to the timestamp of the ObjectId.返回与ObjectId的时间戳相对应的日期。

The following table lists some conversion to date examples:下表列出了一些到日期的转换示例:

Example示例Results结果
{ input: 120000000000.5, to: "date"}
ISODate(“1973-10-20T21:20:00Z”)
{ input: NumberDecimal("1253372036000.50"), to: "date"}
ISODate(“2009-09-19T14:53:56Z”)
{ input: NumberLong("1100000000000"), to: "date"}
ISODate(“2004-11-09T11:33:20Z”)
{ input:  NumberLong("-1100000000000"), to: "date"}
ISODate(“1935-02-22T12:26:40Z”)
{ input: ObjectId("5ab9c3da31c2ab715d421285"), to: "date" }
ISODate(“2018-03-27T04:08:58Z”)
{ input:  "2018-03-03", to: "date" }
ISODate(“2018-03-03T00:00:00Z”)
{ input: "2018-03-20 11:00:06 +0500", to: "date" }
ISODate(“2018-03-20T06:00:06Z”)
{ input: "Friday", to: "date" }
Error
{
   input: "Friday",
   to: "date",
   onError: "Could not convert to type date."
}
“Could not convert to type date.”“无法转换为日期类型。”

See also参阅

$toDate operator, $dateFromString

Converting to an 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
{
   input: "5ab9cbfa31c2ab715d42129",
   to: "objectId",
   onError: "Could not convert to type ObjectId."
}
“Could not convert to type ObjectId.”“无法转换为ObjectId类型。”

See also参阅

$toObjectId operator.

Converting to a String转换为字符串

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

Input Type输入类型Behavior行为
Boolean Returns the boolean value as a string.以字符串形式返回布尔值。
Double Returns the double value as a string.以字符串形式返回双精度值。
Decimal Returns the decimal value as a string.以字符串形式返回十进制值。
Integer Returns the integer value as a string.以字符串形式返回整数值。
Long Returns the long value as a string.以字符串形式返回长值。
ObjectId Returns the ObjectId value as a hexadecimal string..以十六进制字符串的形式返回ObjectId值。
String No-op. Returns the string value.不操作。返回字符串值。
Date Returns 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: NumberInt(2), to: "string"}
“2”
{ input:  NumberLong(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”

See also参阅

$toString operator. $dateToString

Example示例

Create a collection orders with the following documents:使用以下文档创建集合orders

db.orders.insert( [
   { _id: 1, item: "apple", qty: 5, price: 10 },
   { _id: 2, item: "pie", qty: 10, price: NumberDecimal("20.0") },
   { _id: 3, item: "ice cream", qty: 2, price: "4.99" },
   { _id: 4, item: "almonds" },
   { _id: 5, item: "bananas", qty: 5000000000, price: NumberDecimal("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.
// If price or qty values cannot be converted, the conversion returns a string

priceQtyConversionStage = {
   $addFields: {
      convertedPrice: { $convert: { input: "$price", to: "decimal", onError: "Error", onNull: NumberDecimal("0") } },
      convertedQty: { $convert: {
         input: "$qty", to: "int",
         onError:{$concat:["Could not convert ", {$toString:"$qty"}, " to type integer."]},
         onNull: NumberInt("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" : NumberDecimal("50.0000000000000") }
{ "_id" : 2, "totalPrice" : NumberDecimal("200.0") }
{ "_id" : 3, "totalPrice" : NumberDecimal("9.98") }
{ "_id" : 4, "totalPrice" : NumberDecimal("0") }
{ "_id" : 5, "totalPrice" : "NaN" }