Overview
コレクション全体で指定されたフィールドの個別の値をすべて取得するには、 distinct()メソッドを使用します。
サンプル ドキュメント
このガイドの例えに従うには、次のコード スニペットを使用してレストランを説明するドキュメントをmyDB.restaurantsコレクションに挿入します。
const myDB = client.db("myDB");const myColl = myDB.collection("restaurants");
await myColl.insertMany([ { "_id": 1, "restaurant": "White Bear", "borough": "Queens", "cuisine": "Chinese" }, { "_id": 2, "restaurant": "Via Carota", "borough": "Manhattan", "cuisine": "Italian" }, { "_id": 3, "restaurant": "Borgatti's", "borough": "Bronx", "cuisine": "Italian" }, { "_id": 4, "restaurant": "Tanoreen", "borough": "Brooklyn", "cuisine": "Middle Eastern" }, { "_id": 5, "restaurant": "Äpfel", "borough": "Queens", "cuisine": "German" }, { "_id": 6, "restaurant": "Samba Kitchen", "borough": "Manhattan", "cuisine": "Brazilian" },]);distinct
distinct()メソッドでは、パラメータとしてドキュメント フィールドが必要です。 メソッドの出力を調整するには、次の任意のパラメーターを指定できます。
結果を改善するための
queryパラメータ照合ルールを設定するための
optionsパラメータ
distinct()メソッドは、フィールドの個別の値の配列に解決される Promise を返します。このページの例に示すように、await を使用して一意の値の配列にアクセスします。
ドキュメント フィールド パラメーター
ドキュメント フィールドの名前を渡して、フィールドの一意の値のリストを返します。
例
"Queens"と"Manhattan"の各値は、サンプル ドキュメントに複数回表示されます。 ただし、次の例では、 boroughフィールドの一意の値を検索します。
// specify "borough" as the field to return values forconst distinctValues = await myColl.distinct("borough");console.log(distinctValues);このコードは、次のborough値を出力します。
[ "Bronx", "Brooklyn", "Manhattan", "Queens" ]クエリ パラメータ
クエリ パラメータを指定すると、クエリに一致するドキュメントの一意の値を返すことができます。
クエリフィルターの作成の詳細については、「 クエリの指定」を参照してください。
例
次の例では、 cuisineフィールドの個別の値を出力しますが、 "Brooklyn"のレストランは除外しています。
// exclude Brooklyn restaurants from the outputconst query = { borough: { $ne: "Brooklyn" }};
// find the filtered distinct values of "cuisine"const distinctValues = await myColl.distinct("cuisine", query);console.log(distinctValues);この場合、クエリフィルターは、 "Brooklyn"を除くすべての または の値と一致します。 これにより、 distinct()は 1 つのcuisine値である"Middle Eastern"を出力するのを防ぎます。 このコードでは、次の値が出力されます。
[ "Brazilian", "Chinese", "German", "Italian" ]Options Parameter
collationフィールドをoptionsパラメータとして定義することで、 distinct()メソッドに照合を指定できます。 このフィールドを使用すると、 stringの順序付けと比較のリージョン ルールを設定できます。
照合を適用する手順については、 「 CRUD操作の構成 」ガイドの「 照合 」セクションを参照してください。
注意
optionsパラメータを使用する場合は、 queryパラメータも指定する必要があります。 クエリフィルターを使用しない場合は、クエリを{}として定義します。
例
次の例では、個別のrestaurant値を出力するときに、 collationフィールドを使用してドイツ語の順序付け規則を指定します。
// define an empty query documentconst query = {};// specify German string ordering conventionsconst options = { collation: { locale: "de" }};
const distinctValues = await myColl.distinct("restaurant", query, options);console.log(distinctValues);この場合、ドイツの string 順序付け規則では、"O" で始まる単語が "B" で始まる単語の前に配置されます。 このコードでは、以下の内容が出力されます。
[ "Äpfel", "Borgatti's", "Samba Kitchen", "Tanoreen", "Via Carota", "White Bear" ]collationフィールドを指定しない場合、出力順序はデフォルトのバイナリ照合ルールに従います。 これらのルールでは、アクセントが付いていない最初の文字を持つ単語の後に、"O" で始まる単語を配置します。
[ "Borgatti's", "Samba Kitchen", "Tanoreen", "Via Carota", "White Bear", "Äpfel" ]distinct() の例: 完全なファイル
注意
セットアップ例
この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoDB への接続」ガイドを参照してください。この例では、Atlas サンプル データセットに含まれる sample_mflix データベースの movies コレクションも使用します。MongoDB Get Startedに従って、MongoDB Atlasの無料クラスター上のデータベースに読み込むことができます。
次のスニペットは、moviesコレクションから yearドキュメントフィールドの個別の値のリストを取得します。クエリドキュメントを使用して、directors 配列に "Barbra Streisand" を含む映画を照合します。
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() { try { // Get the database and collection on which to run the operation const database = client.db("sample_mflix"); const movies = database.collection("movies");
// Specify the document field to find distinct values for const fieldName = "year";
// Specify an optional query document to narrow results const query = { directors: "Barbra Streisand" };
// Execute the distinct operation const distinctValues = await movies.distinct(fieldName, query);
// Print the result console.log(distinctValues); } finally { await client.close(); }}run().catch(console.dir);import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>";
const client = new MongoClient(uri);
interface Movie { directors: string; year: number;}
async function run() { try { // define a database and collection on which to run the method const database = client.db("sample_mflix"); const movies = database.collection<Movie>("movies");
const distinctValues = await movies.distinct("year", { directors: "Barbra Streisand", });
console.log(distinctValues); } finally { await client.close(); }}run().catch(console.dir);上記の例を実行すると、次の出力が生成されます。
[ 1983, 1991, 1996 ]API ドキュメント
このガイドで説明した型やメソッドの詳細については、次の API ドキュメントを参照してください。