연 $switch 산자는 일련의 조건을 평가하고 true로 평가되는 첫 번째 조건에 따라 값을 반환하는 데 사용됩니다. 집계 파이프라인 내에서 복잡한 조건부 논리를 구현해야 하는 경우에 유용합니다.
문법
{
$switch: {
branches: [
{ case: <expression>, then: <expression> },
{ case: <expression>, then: <expression> }
],
default: <expression>
}
}
매개 변수
| 매개 변수 | Description |
|---|---|
| 분기 | 각각을 포함하는 문서의 배열입니다. |
| 경우 | 또는 true false |
| then | 연결된 식이 로 계산되는 case 경우 반환할 식입니다. true |
| 기본값 | 계산되는 식이 case 없는 경우 반환할 true식입니다. 이 필드는 선택적입니다. |
예시
스토어 컬렉션에서 이 샘플 문서를 고려합니다.
{
"_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: 정규직 및 파트타임 수에 따라 직원 유형을 확인하려면
이 쿼리는 수에 따라 직원의 유형을 결정합니다.
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"
}
]