对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$toInt(表达式操作符)

$toInt

将值转换为整数。如果该值无法转换为整数,则 $toInt 出错。如果该值为空或缺失,$toInt 将返回空值。

$toInt 通过以下语法实现:

{
$toInt: <expression>
}

$toInt 采用任何有效的表达式

$toInt 是以下 $convert 表达式的简写:

{ $convert: { input: <expression>, to: "int" } }

提示

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

输入类型
行为

布尔

返回0false 。返回
1true

double

返回截断后的值。

截断后的 double 值必须介于整数的最小值与最大值之间。

如果 double 值的截断值小于最小整数值或大于最大整数值,则无法转换该 double 值。

Decimal 数据类型

返回截断后的值。

截断后的十进制值必须介于整数的最小值与最大值之间。

如果十进制数值的截断值小于最小整数值或大于最大整数值,则无法转换该十进制数值。

整型

不操作。返回整数值。

Long

以整数形式返回该长整型值。

该长整型值必须介于整数的最小值与最大值范围之间。

不能转换小于最小整数值或大于最大整数值的长整数值。

字符串

以整数形式返回字符串的数值。

字符串值必须是以 10 为基数的整数;例如"-5""123456")。

您无法转换浮点数、十进制数或非以 10 为基数的字符串值(例如 "-5.0""0x6400")

提示

要转换 10 以外的字符串,请使用 $convertbase 选项。

下表列出了转换为整数的部分示例:

例子
结果

$toInt: true

1

$toInt: false

0

$toInt: 1.99999

1

$toInt: Decimal128("5.5000")

5

$toInt: Decimal128("9223372036000.000")

错误

$toInt: Long("5000")

5000

$toInt: Long("922337203600")

错误

$toInt: "-2"

-2

$toInt: "2.5"

错误

$toInt: null

null

使用以下文档创建集合 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 }
] )

以下聚合操作:

  • qty 转换为整数,

  • 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
] )

该操作将返回以下文档:

{ _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") }

注意

如果转换操作遇到错误,聚合操作会停止并抛出错误。要覆盖此行为,请改为使用 $convert

在此页面上