运算符 $toInt 将指定的值转换为整数值。
Syntax
运算符的 $toInt 语法为:
{
$toInt: < expression >
}
参数
| 参数 | Description |
|---|---|
expression |
要转换为整数值的指定值 |
例子
请考虑商店集合中的这个示例文档。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
示例 1:将 Double 值转换为整数值
若要将纬度字段的值从 double 转换为 int,请在字段上使用 $toInt 运算符运行查询以进行转换。
db.stores.aggregate([{
$match: {
_id: "b0107631-9370-4acd-aafa-8ac3511e623d"
}
}, {
$project: {
originalLatitude: "$location.lat",
latitudeAsInt: {
$toInt: "$location.lat"
}
}
}])
此查询返回以下结果:
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"originalLatitude": 72.8377,
"latitudeAsInt": 72
}
]
示例 2:将字符串值转换为整数值
要将字符串“72”转换为整数值,可以在值上使用 $toInt 运算符运行查询来进行转换。
db.stores.aggregate([{
$match: {
_id: "b0107631-9370-4acd-aafa-8ac3511e623d"
}
}, {
$project: {
originalLatitude: "$location.lat",
latitudeAsInt: {
$toInt: {
$toString: "72"
}
}
}
}])
此查询返回以下结果:
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"originalLatitude": 72.8377,
"latitudeAsInt": 72
}
]
但是,以下查询返回错误,因为字符串“72.0”不是整数值的字符串表示形式。
db.stores.aggregate([{
$match: {
_id: "b0107631-9370-4acd-aafa-8ac3511e623d"
}
}, {
$project: {
originalLatitude: "$location.lat",
latitudeAsInt: {
$toInt: {
$toString: "72.0"
}
}
}
}])
此查询返回以下错误消息 - “未能分析 $convert 中的数字 ”72.0”
此表根据输入的数据类型来描述$toInt运算符的预期行为。
| 值类型 | 行为/输出 |
|---|---|
| 布尔值为真 | 输出结果 -> 1 |
| 布尔值假 | 输出 -> 0 |
| 倍数值 例如,72.0 | 输出 -> 72 |
| 整数值的字符串表示形式。 例如,“72” | 输出 -> 72 |
| 双精度值的字符串表示形式。 例如,“72.0” | 输出 -> 错误 |
| 空值 | 输出 -> null |
相关内容
- 查看用于 从 MongoDB 迁移到 Azure DocumentDB 的选项。
- 详细了解 与 MongoDB 的功能兼容性。