Definition定义
$toIntConverts a value to an integer. If the value cannot be converted to an integer,将值转换为整数。如果该值无法转换为整数,则$toInterrors. If the value is null or missing,$toIntreturns null.$toInt错误。如果该值为null或缺失,$toInt将返回null。$toInthas the following syntax:具有以下语法:{
$toInt: <expression>
}The$toInttakes any valid expression.$toInt接受任何有效表达式。The$toIntis a shorthand for the following$convertexpression:$toInt是以下$convert表达式的简写:{ $convert: { input: <expression>, to: "int" } }Tip
Behavior行为
The following table lists the input types that can be converted to an integer:下表列出了可以转换为整数的输入类型:
0 for false.false返回0。1 for true.true返回1。 | |
| |
| Decimal |
|
| |
|
The following table lists some conversion to integer examples:下表列出了一些转换为整数的示例:
$toInt: true | 1 |
$toInt: false | 0 |
$toInt: 1.99999 | 1 |
$toInt: Decimal128("5.5000") | 5 |
$toInt: Decimal128("9223372036000.000") | Error |
$toInt: Long("5000") | 5000 |
$toInt: Long("922337203600") | Error |
$toInt: "-2" | -2 |
$toInt: "2.5" | Error |
$toInt: null | null |
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" , qty: "5", price: 5 }
] )
The following aggregation operation:以下聚合操作:
converts将qtyto an integer,qty转换为整数,converts将priceto a decimal,price转换为小数,calculates the total price:计算总价:
// Define stage to add convertedPrice and convertedQty fields with the converted price and qty values<定义阶段以添加转换价格和转换数量字段,其中包含转换价格和数量值</span>
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") }
Note
If the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use 如果转换操作遇到错误,聚合操作将停止并抛出错误。要覆盖此行为,请改用$convert instead.$converter。