運算子 $cmp 會比較兩個指定的值。 如果第一個值小於第二個值,則$cmp運算符會傳回 -1;如果兩個值相等,則傳回 0;如果第一個值大於第二個值,則傳回 1。
語法
{
$cmp: [<firstValueToCompare>, <secondValueToCompare>]
}
參數
| 參數 | Description |
|---|---|
<firstValueToCompare> |
第一個值,由 $cmp 運算符比較第二個值 |
<secondValueToCompare> |
$cmp 運算子所比較的第二個值 |
範例
請參考商店集合中的此範例檔。
{
"_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 - 比較商店總銷售額與 $25,000
若要比較布爾德創新公司內商店的總銷售額與 25,000 美元,請先執行查詢來篩選商店的公司名稱。 然後,使用 $cmp 比較 sales.totalSales 字段與 25000。 最後,只投影結果商店的名稱和總銷售額。
db.stores.aggregate([{
$match: {
company: {
$in: ["Boulder Innovations"]
}
}
}, {
$project: {
name: 1,
"sales.salesByCategory.totalSales": 1,
greaterThan25000: {
$cmp: ["$sales.revenue", 25000]
}
}
}])
此查詢傳回的前兩個結果是:
[
{
"_id": "a5040801-d127-4950-a320-e55f6aed4b36",
"name": "Boulder Innovations | DJ Equipment Pantry - West Christopher",
"sales": {
"salesByCategory": [
{
"totalSales": 21522
}
]
},
"greaterThan25000": -1
},
{
"_id": "bb6e097a-e204-4b64-9f13-5ae8426fcc76",
"name": "Boulder Innovations | Kitchen Appliance Outlet - Lake Chazville",
"sales": {
"salesByCategory": [
{
"totalSales": 24062
},
{
"totalSales": 24815
}
]
},
"greaterThan25000": 1
}
]