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
パラメータ
ドキュメント フィールド パラメーター
ドキュメント フィールドの名前を渡して、フィールドの一意の値のリストを返します。
例
"Queens"
と"Manhattan"
の各値は、サンプル ドキュメントに複数回表示されます。 ただし、次の例では、 borough
フィールドの一意の値を検索します。
// specify "borough" as the field to return values for const cursor = myColl.distinct("borough"); for await (const doc of cursor) { console.dir(doc); }
このコードは、次のborough
値を出力します。
[ "Bronx", "Brooklyn", "Manhattan", "Queens" ]
クエリ パラメータ
クエリ パラメータを指定すると、クエリに一致するドキュメントの一意の値を返すことができます。
クエリフィルターの作成の詳細については、「 クエリの指定」を参照してください。
例
次の例では、 cuisine
フィールドの個別の値を出力しますが、 "Brooklyn"
のレストランは除外しています。
// exclude Brooklyn restaurants from the output const query = { borough: { $ne: "Brooklyn" }}; // find the filtered distinct values of "cuisine" const cursor = myColl.distinct("cuisine", query); for await (const doc of cursor) { console.dir(doc); }
この場合、クエリフィルターは、 "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 document const query = {}; // specify German string ordering conventions const options = { collation: { locale: "de" }}; const cursor = myColl.distinct("restaurant", query, options); for await (const doc of cursor) { console.dir(doc); }
この場合、ドイツの 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への接続 ガイドを参照してください。この例では、movies
sample_mflix
Atlasサンプルデータセット に含まれる データベースの コレクションも使用します。「Atlas を使い始める」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。
次のスニペットは、movies
コレクションから year
ドキュメントフィールドの個別の値のリストを取得します。クエリドキュメントを使用して、director
配列に "Barbara Streisand"
を含む映画を照合します。
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 11 // Get the database and collection on which to run the operation 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Specify the document field to find distinct values for 16 const fieldName = "year"; 17 18 // Specify an optional query document to narrow results 19 const query = { directors: "Barbra Streisand" }; 20 21 // Execute the distinct operation 22 const distinctValues = await movies.distinct(fieldName, query); 23 24 // Print the result 25 console.log(distinctValues); 26 } finally { 27 await client.close(); 28 } 29 } 30 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Movie { 9 directors: string; 10 year: number; 11 } 12 13 async function run() { 14 try { 15 // define a database and collection on which to run the method 16 const database = client.db("sample_mflix"); 17 const movies = database.collection<Movie>("movies"); 18 19 const distinctValues = await movies.distinct("year", { 20 directors: "Barbra Streisand", 21 }); 22 23 console.log(distinctValues); 24 } finally { 25 await client.close(); 26 } 27 } 28 run().catch(console.dir);
上記の例を実行すると、次の出力が生成されます。
[ 1983, 1991, 1996 ]
API ドキュメント
このガイドで説明した型やメソッドの詳細については、次の API ドキュメントを参照してください。