次の方法で共有


distinct

distinct コマンドは、1 つのコレクション全体で指定されたフィールドの一意の値を検索するために使用されます。 このコマンドは、すべてのドキュメントを取得せずにフィールドの個別の値のセットを識別する必要がある場合や、一意の値に基づいてフィルター処理やグループ化などの操作を実行する必要がある場合に便利です。

構文

distinct コマンドの基本的な構文は次のとおりです。

db.collection.distinct(field, query, options)
  • field: 返された個別の値を受け取るフィールド。
  • query:随意。 個別の値の取得元となるドキュメントを指定するクエリ。
  • options:随意。 コマンドのその他のオプション。

例示

提供されているサンプル JSON 構造を使用した例を次に示します。

例 1: 売上で個別のカテゴリを検索する

salesByCategory配列内の個別のcategoryNameを検索するには:

db.stores.distinct("sales.salesByCategory.categoryName")

サンプル出力

[mongos] StoreData> db.stores.distinct("sales.salesByCategory.categoryName")
[
  {
    _id: 'Discount Derby',
    discounts: [
      { categoryName: 'Bath Sheets', discountPercentage: 25 },
      { categoryName: 'Tablecloths', discountPercentage: 25 },
      { categoryName: 'Drapes', discountPercentage: 25 }
    ]
  }
]
[mongos] StoreData> db.stores.distinct("sales.salesByCategory.categoryName")
[
  'Music Theory Books',
  'Superfoods',
  'Harmonicas',
  'Garden Tools',
  ... 883 more items
]  

例 2: 昇格イベントで個別のイベント名を検索する

promotionEvents配列内の個別のeventNameを検索するには:

db.stores.distinct("promotionEvents.eventName")

サンプル出力

[mongos] StoreData> db.stores.distinct("promotionEvents.eventName")
[
{
    _id: 'Super Saver Celebration',
    discounts: [
      { categoryName: 'Face Towels', discountPercentage: 25 },
      { categoryName: 'Printer Ribbons', discountPercentage: 25 },
      { categoryName: 'Chromebooks', discountPercentage: 25 }
    ]
    }
]

例 3: 特定のイベントの個別の割引率を検索する

"Summer Sale" イベントのdiscounts配列で個別のdiscountPercentageを見つけるには:

db.stores.distinct("promotionEvents.discounts.discountPercentage", { "promotionEvents.eventName": "Incredible Discount Days" })

サンプル出力

[mongos] StoreData> db.stores.distinct("promotionEvents.discounts.discountPercentage", { "promotionEvents.eventName": "Incredible Discount Days" })
[
   6, 17, 22, 25,  9, 15, 14,
   7, 12, 19, 24,  5, 20, 10,
  23, 16, 18, 21, 13, 11,  8
]