Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Node.js ドライバー
/ /

Retrieve Distinct Values

コレクション全体で指定されたフィールドの個別の値をすべて取得するには、 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()メソッドでは、パラメータとしてドキュメント フィールドが必要です。 メソッドの出力を調整するには、次の任意のパラメーターを指定できます。

  • 結果を改善するための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" ]

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" ]

注意

セットアップ例

この例では、接続 URI を使用してMongoDBのインスタンスに接続します。MongoDBインスタンスへの接続の詳細については、 MongoDBへの接続 ガイドを参照してください。この例では、movies sample_mflixAtlasサンプルデータセット に含まれる データベースの コレクションも使用します。Atlas を使い始める」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。

次のスニペットは、moviesコレクションから yearドキュメントフィールドの個別の値のリストを取得します。クエリドキュメントを使用して、director 配列に "Barbara Streisand" を含む映画を照合します。

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async 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}
30run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 directors: string;
10 year: number;
11}
12
13async 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}
28run().catch(console.dir);

上記の例を実行すると、次の出力が生成されます。

[ 1983, 1991, 1996 ]

このガイドで説明した型やメソッドの詳細については、次の API ドキュメントを参照してください。

戻る

ドキュメントをカウント

項目一覧