$switch
运算符用于计算一系列条件,并根据计算结果为 true 的第一个条件返回值。 需要在聚合管道中实现复杂的条件逻辑时,这非常有用。
语法
$switch
运算符的语法如下所示:
{
$switch: {
branches: [
{ case: <expression>, then: <expression> },
{ case: <expression>, then: <expression> },
...
],
default: <expression>
}
}
参数
说明 | |
---|---|
分支 | 一个文档数组,每个文档都包含 |
case | 计算结果为 true 或 false 的表达式 |
然后在受影响的域控制器上,运行 | 关联的 case 表达式的计算结果为 true 时返回的表达式 |
default | 没有一个 case 表达式的计算结果为 true 时返回的表达式。 此字段可选。 |
示例
让我们通过以下示例 json 来了解用法。
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
"location": {
"lat": 60.1441,
"lon": -141.5012
},
"staff": {
"totalStaff": {
"fullTime": 2,
"partTime": 0
}
},
"sales": {
"salesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35921
}
],
"fullSales": 3700
},
"promotionEvents": [
{
"eventName": "Bargain Blitz Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 3,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 2,
"Day": 18
}
},
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
}
],
"tag": [
"#ShopLocal",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
]
}
根据员工计数确定员工的类型。
db.stores.aggregate([
{
$project: {
name: 1,
staffType: {
$switch: {
branches: [
{
case: { $eq: ["$staff.totalStaff.partTime", 0] },
then: "Only Full time"
},
{
case: { $eq: ["$staff.totalStaff.fullTime", 0] },
then: "Only Part time"
}
],
default: "Both"
}
}
}
},
// Limit the result to the first 3 documents
{ $limit: 3 }
])
此查询将返回以下文档。
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
"staffType": "Only Full time"
},
{
"_id": "649626c9-eda1-46c0-a27f-dcee19d97f41",
"name": "VanArsdel, Ltd. | Musical Instrument Outlet - East Cassie",
"staffType": "Both"
},
{
"_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34",
"name": "Northwind Traders | Bed and Bath Place - West Oraland",
"staffType": "Both"
}
]