$first

$first 연산자는 쿼리에 지정된 하나 이상의 필드에서 문서를 정렬하고 필터링 조건과 일치하는 첫 번째 문서를 반환합니다. 정렬 순서가 지정되지 않으면 순서가 정의되지 않습니다.

문법

{
    $first: <expression>
}

매개 변수

매개 변수 Description
expression 결과 집합에서 첫 번째 문서를 평가하고 반환할 식입니다.

예시

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

{
    "_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 회사에서 가장 최근에 업데이트된 저장소를 검색하려면 쿼리를 실행하여 "First Up Consultants" 회사에 속한 모든 문서를 가져오고, 결과 문서를 lastUpdated 필드의 오름차순으로 정렬하고, 결과 집합의 첫 번째 문서를 반환합니다.

db.stores.aggregate([{
    $match: {
        company: {
            $in: ["First Up Consultants"]
        }
    }
}, {
    $sort: {
        lastUpdated: 1
    }
}, {
    $group: {
        _id: "$company",
        firstUpdated: {
            $first: "$lastUpdated"
        }
    }
}])

이 쿼리는 다음 결과를 반환합니다.

[
  {
      "_id": "First Up Consultants",
      "firstUpdated": "ISODate('2025-06-11T10:48:01.291Z')"
  }
]

예제 2: 저장소당 판매액별 첫 번째 범주 가져오기

각 저장소 내에서 첫 번째 범주(사전순)를 검색하려면 쿼리를 실행하여 각 저장소 내의 판매 범주 목록을 정렬하고 저장소당 정렬된 결과 집합에서 첫 번째 범주를 반환합니다.

db.stores.aggregate([{
        $unwind: "$sales.salesByCategory"
    },
    {
        $sort: {
            "_id": 1,
            "sales.salesByCategory.categoryName": 1
        }
    },
    {
        $group: {
            _id: "$_id",
            storeName: {
                $first: "$name"
            },
            totalSales: {
                $first: "$sales.totalSales"
            },
            firstCategory: {
                $first: {
                    categoryName: "$sales.salesByCategory.categoryName",
                    categoryTotalSales: "$sales.salesByCategory.totalSales"
                }
            }
        }
    }
])

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

[
    {
        "_id": "64ec6589-068a-44a6-be5b-9d37bb0a90f1",
        "storeName": "First Up Consultants | Computer Gallery - West Cathrine",
        "totalSales": 186829,
        "firstCategory": {
            "categoryName": "Cases",
            "categoryTotalSales": 36386
        }
    },
    {
        "_id": "14343900-2a5c-44bf-a52b-9efe63579866",
        "storeName": "Northwind Traders | Home Improvement Closet - West Evanside",
        "totalSales": 35371,
        "firstCategory": {
            "categoryName": "Doors",
            "categoryTotalSales": 21108
        }
    }
]

예제 3: 스토어당 첫 번째 프로모션 이벤트 가져오기

각 저장소에 대한 첫 번째 승격 이벤트를 검색하려면 쿼리를 실행하여 startDate를 통해 각 저장소 내의 승격 이벤트 목록을 정렬하고 저장소당 정렬된 결과 집합에서 첫 번째 이벤트를 반환합니다.

시작 날짜에 따라 각 저장소에 대한 첫 번째 프로모션 이벤트를 가져옵니다.

db.stores.aggregate([{
        $unwind: "$promotionEvents"
    },
    {
        $sort: {
            "_id": 1,
            "promotionEvents.promotionalDates.startDate.Year": 1,
            "promotionEvents.promotionalDates.startDate.Month": 1,
            "promotionEvents.promotionalDates.startDate.Day": 1
        }
    },
    {
        $group: {
            _id: "$_id",
            storeName: {
                $first: "$name"
            },
            firstPromotionEvent: {
                $first: {
                    eventName: "$promotionEvents.eventName",
                    startYear: "$promotionEvents.promotionalDates.startDate.Year",
                    startMonth: "$promotionEvents.promotionalDates.startDate.Month"
                }
            }
        }
    }
])

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

[
    {
        "_id": "64ec6589-068a-44a6-be5b-9d37bb0a90f1",
        "storeName": "First Up Consultants | Computer Gallery - West Cathrine",
        "firstPromotionEvent": {
            "eventName": "Crazy Markdown Madness",
            "startYear": 2024,
            "startMonth": 6
        }
    },
    {
        "_id": "a58d0356-493b-44e6-afab-260aa3296930",
        "storeName": "Fabrikam, Inc. | Outdoor Furniture Nook - West Lexie",
        "firstPromotionEvent": {
            "eventName": "Price Drop Palooza",
            "startYear": 2023,
            "startMonth": 9
        }
    }
]