$rank運運算元會為資料集分割區內的每個文件指派排名。 排名是根據指定的排序順序來決定的。
語法
{
$setWindowFields: {
partitionBy: < expression > ,
sortBy: {
< field >: < order >
},
output: {
< outputField >: {
$rank: {}
}
}
}
}
參數
| 參數 | Description |
|---|---|
partitionBy |
指定將文件分組為分割區的運算式。 如果省略,則所有文件都會被視為單一分割區。 |
sortBy |
定義排名的排序順序。 必須指定 $rank。 |
output |
包含儲存排名值的欄位。 |
範例
請參考商店集合中的此範例檔。
{
"_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:按銷售量對商店進行排名
若要依銷售量對「First Up Consultants」公司內的所有商店進行排名,請先執行查詢以分割公司內的商店。 然後,以銷售量的遞增順序排序產生的商店,並使用$rank運算子對結果集中排序的文件進行排名。
db.stores.aggregate([{
"$match": {
"company": {
"$in": ["First Up Consultants"]
}
}
}, {
"$setWindowFields": {
"partitionBy": "$company",
"sortBy": {
"sales.totalSales": -1
},
"output": {
"rankBySales": {
"$rank": {}
}
}
}
}, {
"$project": {
"company": 1,
"name": 1,
"rankBySales": 1
}
}])
此查詢傳回的前三個結果為:
[
{
"_id": "a0386810-b6f8-4b05-9d60-e536fb2b0026",
"name": "First Up Consultants | Electronics Stop - South Thelma",
"company": "First Up Consultants",
"rankBySales": 1
},
{
"_id": "ad8af64a-d5bb-4162-9bb6-e5104126566d",
"name": "First Up Consultants | Electronics Emporium - South Carmenview",
"company": "First Up Consultants",
"rankBySales": 2
},
{
"_id": "39acb3aa-f350-41cb-9279-9e34c004415a",
"name": "First Up Consultants | Bed and Bath Pantry - Port Antone",
"company": "First Up Consultants",
"rankBySales": 3
}
]