如果輸入表達式是數值類型,運算符 $isNumber 會傳回 true。 運算子 $isNumber 會針對任何其他類型的表達式傳回 false。
語法
{
$isNumber: < 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 值是否為數位
若要確認緯度欄位的值是否為數值,請使用 $isNumber 運算子執行查詢,以驗證欄位的雙精度浮點數值為數字。
db.stores.aggregate([{
$match: {
_id: "b0107631-9370-4acd-aafa-8ac3511e623d"
}
}, {
$project: {
originalLatitude: "$location.lat",
latitudeIsNumber: {
$isNumber: "$location.lat"
}
}
}])
此查詢會傳回下列結果:
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"originalLatitude": 72.8377,
"latitudeIsNumber": true
}
]
範例 2:檢查 Int 值是否為數位
若要確認 totalSales 欄位的值是否為數值,請使用 $isNumber 運算符執行查詢,以驗證欄位中雙精度的值是否為數字。
db.stores.aggregate([{
$match: {
_id: "b0107631-9370-4acd-aafa-8ac3511e623d"
}
}, {
$project: {
originalTotalSales: "$sales.totalSales",
totalSalesIsNumber: {
$isNumber: "$sales.totalSales"
}
}
}])
此查詢會傳回下列結果:
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"originalTotalSales": 9366,
"totalSalesIsNumber": true
}
]
範例 3:檢查字串是否為數位
若要確認_id域的值是否為數值,請使用 $isNumber 運算元執行查詢,以驗證字段的字串值不是數位。
db.stores.aggregate([{
$match: {
_id: "b0107631-9370-4acd-aafa-8ac3511e623d"
}
}, {
$project: {
idIsNumber: {
$isNumber: "$_id"
}
}
}])
此查詢會傳回下列結果:
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"idIsNumber": false
}
]