次の方法で共有


$top

適用対象: MongoDB 仮想コア

$top アキュムレータ演算子は、指定された並べ替え順序に基づいて、グループの最上位の要素を返します。 並べ替えと選択を 1 つの操作で組み合わせることで、個別の並べ替えステージを必要とせずに、最大値または最小値を効率的に検索することができます。

構文

$top アキュムレータ演算子の構文は次のとおりです。

{
  $group: {
    _id: <expression>,
    <field>: { 
      $top: {
        sortBy: { <field1>: <sort order>, <field2>: <sort order>, ... },
        output: <expression>
      }
    }
  }
}

パラメーター

説明
sortBy フィールド名と並べ替え方向 (昇順の場合は 1、降順の場合は -1) を指定したドキュメントを使用して、並べ替え順序を指定します。
output 最上位のドキュメントから返されるフィールドまたは値を指定する式。

stores データセットからのサンプル json の使用方法を理解しましょう。

{
  "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
  "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
  "sales": {
    "totalSales": 151864,
    "salesByCategory": [
      {
        "categoryName": "Sound Bars",
        "totalSales": 2120
      },
      {
        "categoryName": "Home Theater Projectors",
        "totalSales": 45004
      },
      {
        "categoryName": "Game Controllers",
        "totalSales": 43522
      },
      {
        "categoryName": "Remote Controls",
        "totalSales": 28946
      },
      {
        "categoryName": "VR Games",
        "totalSales": 32272
      }
    ]
  },
  "promotionEvents": [
    {
      "eventName": "Massive Markdown Mania",
      "promotionalDates": {
        "startDate": {
          "Year": 2023,
          "Month": 6,
          "Day": 29
        }
      },
      "discounts": [
        {
          "categoryName": "DVD Players",
          "discountPercentage": 14
        },
        {
          "categoryName": "Televisions",
          "discountPercentage": 22
        }
      ]
    }
  ]
}

例 1: 店舗ごとに最も売れているカテゴリを取得する

各店舗で最も売れているカテゴリを検索します。

db.stores.aggregate([
  { $unwind: "$sales.salesByCategory" },
  {
    $group: {
      _id: "$_id",
      storeName: { $first: "$name" },
      topSellingCategory: {
        $top: {
          sortBy: { "sales.salesByCategory.totalSales": -1 },
          output: {
            categoryName: "$sales.salesByCategory.categoryName",
            totalSales: "$sales.salesByCategory.totalSales"
          }
        }
      }
    }
  }
])

これにより、各店舗の最も売れているカテゴリを示す出力が生成されます。

[
  {
    _id: 'b1d86d1f-8705-4157-b64c-a9eda0df4921',
    storeName: 'VanArsdel, Ltd. | Baby Products Haven - West Kingfort',
    topSellingCategory: { categoryName: 'Baby Monitors', totalSales: 49585 }
  },
  {
    _id: '22e6367e-8341-415f-9795-118d2b522abf',
    storeName: 'Adatum Corporation | Outdoor Furniture Mart - Port Simone',
    topSellingCategory: { categoryName: 'Outdoor Benches', totalSales: 4976 }
  },
.
.
.
]

例 2: カテゴリ別の最高割引率を取得する

各店舗のすべてのプロモーション イベントで、割引率が最も高いカテゴリを検索します。

db.stores.aggregate([
  { $unwind: "$promotionEvents" },
  { $unwind: "$promotionEvents.discounts" },
  {
    $group: {
      _id: "$_id",
      storeName: { $first: "$name" },
      highestDiscount: {
        $top: {
          sortBy: { "promotionEvents.discounts.discountPercentage": -1 },
          output: {
            categoryName: "$promotionEvents.discounts.categoryName",
            discountPercentage: "$promotionEvents.discounts.discountPercentage",
            eventName: "$promotionEvents.eventName"
          }
        }
      }
    }
  }
])

これにより、各店舗の割引率が最も高いカテゴリが表示されます。

[
  {
    _id: '64ec6589-068a-44a6-be5b-9d37bb0a90f1',
    storeName: 'First Up Consultants | Computer Gallery - West Cathrine',
    highestDiscount: {
      categoryName: 'Gaming Accessories',
      discountPercentage: 24,
      eventName: 'Crazy Markdown Madness'
    }
  },
  {
    _id: 'a58d0356-493b-44e6-afab-260aa3296930',
    storeName: 'Fabrikam, Inc. | Outdoor Furniture Nook - West Lexie',
    highestDiscount: {
      categoryName: 'Fire Pits',
      discountPercentage: 22,
      eventName: 'Savings Showdown'
    }
  },
.
.
.
]