distinct コマンドは、1 つのコレクション全体で指定されたフィールドの一意の値を検索するために使用されます。 このコマンドは、すべてのドキュメントを取得せずにフィールドの個別の値のセットを識別する必要がある場合や、一意の値に基づいてフィルター処理やグループ化などの操作を実行する必要がある場合に便利です。
構文
distinct コマンドの基本的な構文は次のとおりです。
db.collection.distinct(field, query, options)
-
field: 返された個別の値を受け取るフィールド。 -
query: 省略可能。 個別の値の取得元となるドキュメントを指定するクエリ。 -
options: 省略可能。 コマンドのその他のオプション。
例示
提供されているサンプル JSON 構造を使用した例を次に示します。
例 1: 売上で個別のカテゴリを検索する
categoryName配列内の個別のsalesByCategoryを検索するには:
db.stores.distinct("sales.salesByCategory.categoryName")
サンプル出力
[
"Music Theory Books",
"Superfoods",
"Harmonicas",
"Garden Tools"
]
例 2: 昇格イベントで個別のイベント名を検索する
eventName配列内の個別のpromotionEventsを検索するには:
db.stores.distinct("promotionEvents.eventName")
サンプル出力
[
"Super Saver Celebration",
"Incredible Discount Days"
]
例 3: 特定のイベントの個別の割引率を検索する
"Summer Sale" イベントのdiscountPercentage配列で個別のdiscountsを見つけるには:
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
]