On this page本页内容
$toInt
New in version 4.0.在版本4.0中新增。
Converts a value to an integer. 将值转换为整数。If the value cannot be converted to an integer, 如果该值无法转换为整数,则$toInt
errors. $toInt
会出错。If the value is null or missing, 如果值为$toInt
returns null.null
或缺失,$toInt
将返回null
。
$toInt
has the following syntax:语法如下:
{
$toInt: <expression>
}
The $toInt
takes any valid expression.$toInt
接受任何有效表达式。
The $toInt
is a shorthand for the following $convert
expression:$toInt
是以下$convert
表达式的缩写:
{ $convert: { input: <expression>, to: "int" } }
The following table lists the input types that can be converted to an integer:下表列出了可以转换为整数的输入类型:
Boolean |
|
Double |
|
Decimal |
|
Integer | |
Long |
|
String |
|
The following table lists some conversion to integer examples:下表列出了一些转换为整数的示例:
$toInt: true | 1 |
$toInt: false | 0 |
$toInt: 1.99999 | 1 |
$toInt: NumberDecimal("5.5000") | 5 |
$toInt: NumberDecimal("9223372036000.000") | Error |
$toInt: NumberLong("5000") | 5000 |
$toInt: NumberLong("922337203600") | Error |
$toInt: "-2" | -2 |
$toInt: "2.5" | Error |
$toInt: null | null |
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: NumberDecimal("20.0") }, { _id: 3, item: "ice cream", qty: "2", price: "4.99" }, { _id: 4, item: "almonds" , qty: "5", price: 5 } ] )
The following aggregation operation:以下聚合操作:
qty
to an integer,qty
转换为整数,price
to a decimal,price
转换为小数,// Define stage to add convertedPrice and convertedQty fields with the converted price and qty values priceQtyConversionStage = { $addFields: { convertedPrice: { $toDecimal: "$price" }, convertedQty: { $toInt: "$qty" }, } }; // Define stage to calculate total price by multiplying convertedPrice and convertedQty fields totalPriceCalculationStage = { $project: { item: 1, totalPrice: { $multiply: [ "$convertedPrice", "$convertedQty" ] } } }; db.orders.aggregate( [ priceQtyConversionStage, totalPriceCalculationStage ] )
The operation returns the following documents:该操作返回以下文档:
{ _id: 1, item: 'apple', totalPrice: Decimal128("50") }, { _id: 2, item: 'pie', totalPrice: Decimal128("200.0") }, { _id: 3, item: 'ice cream', totalPrice: Decimal128("9.98") }, { _id: 4, item: 'almonds', totalPrice: Decimal128("25") }