$first

$first演算子は、クエリで指定された 1 つ以上のフィールドでドキュメントを並べ替え、フィルター条件に一致する最初のドキュメントを返します。 並べ替え順序が指定されていない場合、順序は未定義です。

構文

{
    $first: <expression>
}

パラメーター

パラメーター Description
expression 結果セットから最初のドキュメントを評価して返す式

例示

stores コレクションのこのサンプル ドキュメントについて考えてみましょう。

{
    "_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"
                }
            }
        }
    }
])

このクエリによって返される最初の 2 つの結果は次のとおりです。

[
    {
        "_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"
                }
            }
        }
    }
])

このクエリによって返される最初の 2 つの結果は次のとおりです。

[
    {
        "_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
        }
    }
]