$cond

$cond 산자는 조건을 평가하고 결과에 따라 두 식 중 하나를 반환하는 데 사용됩니다. 여러 프로그래밍 언어의 3항 연산자도 비슷합니다. 연산자를 $cond 집계 파이프라인 내에서 사용하여 쿼리에 조건부 논리를 추가할 수 있습니다.

문법

{
   $cond: {
      if: <boolean-expression>,
      then: <true-case>,
      else: <false-case>
   }
}

매개 변수

매개 변수 Description
만약 계산되는 부울 식입니다.
then 조건이 true로 평가되는 경우 if 반환할 식입니다.
그렇지 않으면 조건이 false로 평가되는 경우 if 반환할 식입니다.

예시

스토어 컬렉션에서 이 샘플 문서를 고려합니다.

{
    "_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: 높은 판매 범주 확인

이 쿼리는 임계값 $250,000에 따라 각 범주의 판매액이 "높음" 또는 "낮음"으로 간주되는지 여부를 결정합니다.

db.stores.aggregate([{
        $project: {
            _id: 0,
            storeId: "$storeId",
            category: "$sales.salesByCategory.categoryName",
            sales: "$sales.salesByCategory.totalSales",
            salesCategory: {
                $cond: {
                    if: {
                        $gte: ["$sales.salesByCategory.totalSales", 250000]
                    },
                    then: "High",
                    else: "Low"
                }
            }
        }
    },
    // Limit the result to the first 3 documents
    {
        $limit: 3
    }
])

이 쿼리에서 반환된 처음 세 가지 결과는 다음과 같습니다.

[
    {
        "sales": [
            35921,
            1000
        ],
        "category": [
            "DJ Headphones",
            "DJ Cables"
        ],
        "salesCategory": "High"
    },
    {
        "sales": [
            4760
        ],
        "category": [
            "Guitars"
        ],
        "salesCategory": "High"
    },
    {
        "sales": [
            14697,
            44111,
            37854,
            46211,
            7269,
            25451,
            21083
        ],
        "category": [
            "Washcloths",
            "Innerspring Mattresses",
            "Microfiber Towels",
            "Shower Curtains",
            "Bathrobes",
            "Tablecloths",
            "Bath Accessories"
        ],
        "salesCategory": "High"
    }
]

예제 2: 정규직 또는 파트타임 우위 결정

이 쿼리는 매장이 더 많은 정규직 또는 파트타임 직원을 고용하는지 여부를 결정합니다.

db.stores.aggregate([{
        $project: {
            name: 1,
            staffType: {
                $cond: {
                    if: {
                        $gte: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"]
                    },
                    then: "More Full-Time",
                    else: "More Part-Time"
                }
            }
        }
    },
    // 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": "More Full-Time"
  },
  {
    "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41",
    "name": "VanArsdel, Ltd. | Musical Instrument Outlet - East Cassie",
    "staffType": "More Full-Time"
  },
  {
    "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34",
    "name": "Northwind Traders | Bed and Bath Place - West Oraland",
    "staffType": "More Part-Time"
  }
]