Docs Menu
Docs Home
/ / /
Node.js ドライバー
/ /

複数ドキュメントの検索

collection.find()を使用して、コレクション内の複数のドキュメントをクエリできます。 find()メソッドは、指定したクエリ ドキュメントを使用して、クエリに一致するコレクション内のドキュメントのサブセットを照合します。 クエリ ドキュメントを指定しなかった場合 (あるいは空のドキュメントを指定した場合)、 MongoDB はコレクション内のすべてのドキュメントを返します。 MongoDB のクエリの詳細については、 クエリ ドキュメントに関するドキュメントを参照してください。

結果セットを構成するために、並べ替えプロジェクションなどの追加のクエリ オプションを定義することもできます。 これらは、find() sortオブジェクトとprojection オブジェクトの メソッド呼び出しのオプション パラメータで指定できます。collection.find() を参照してください メソッドに渡すことができるパラメータの詳細については、 を参照してください。

find() メソッドは、クエリの結果を管理する FindCursor を返します。for await...of 構文または以下のカーソルメソッドのいずれかを使用して、一致するドキュメントを繰り返し処理できます。

  • next()

  • toArray()

クエリに一致するドキュメントがない場合、 find()では空のカーソルが返されます。

Node.js ドライバーを使用して接続し、次の環境でホストされている配置にfind()メソッドを使用できます。

  • MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです

  • MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン

  • MongoDB Community: ソースが利用可能で、無料で使用できる、MongoDB の自己管理型バージョン

MongoDB Atlas でホストされている配置の Atlas UI でドキュメントを検索する方法の詳細については、「ドキュメントの作成、表示、更新、および削除」を参照してください。

次のスニペットは、 moviesコレクションからドキュメントを検索します。次のパラメータを使用します。

  • 長さが 15 分未満の映画のみを返すクエリを設定するクエリドキュメント

  • 返されたドキュメントをタイトルの昇順に(アルファベット順で、" A " が " Z " の前に、" 1 " が " 9 " の前に来るように)並べ替えるソート

  • 返されるドキュメントから _id フィールドを明示的に除外し、titleimdb オブジェクト(およびその埋め込みフィールド)のみを明示的に含むプロジェクション

注意

この例を使って MongoDB のインスタンスに接続し、サンプルデータを含むデータベースとやり取りできます。MongoDB インスタンスへの接続とサンプル データセットの読み込みの詳細については、使用例ガイドを参照してください。

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 // Query for movies that have a runtime less than 15 minutes
16 const query = { runtime: { $lt: 15 } };
17
18 const options = {
19 // Sort returned documents in ascending order by title (A->Z)
20 sort: { title: 1 },
21 // Include only the `title` and `imdb` fields in each returned document
22 projection: { _id: 0, title: 1, imdb: 1 },
23 };
24
25 // Execute query
26 const cursor = movies.find(query, options);
27
28 // Print a message if no documents were found
29 if ((await movies.countDocuments(query)) === 0) {
30 console.log("No documents found!");
31 }
32
33 // Print returned documents
34 for await (const doc of cursor) {
35 console.dir(doc);
36 }
37
38 } finally {
39 await client.close();
40 }
41}
42run().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
8type Minutes = number;
9
10interface IMDB {
11 rating: number;
12 votes: number;
13 id: number;
14}
15
16interface Movie {
17 title: string;
18 imdb: IMDB;
19 runtime: Minutes;
20}
21
22async function run() {
23 try {
24 const database = client.db("sample_mflix");
25 const movies = database.collection<Movie>("movies");
26
27 const query = { runtime: { $lt: 15 } };
28 const cursor = movies.find<Movie>(
29 query,
30 {
31 sort: { title: 1 },
32 projection: { _id: 0, title: 1, imdb: 1 },
33 }
34 );
35
36 if ((await movies.countDocuments(query)) === 0) {
37 console.warn("No documents found!");
38 }
39
40 for await (const doc of cursor) {
41 console.dir(doc);
42 }
43 } finally {
44 await client.close();
45 }
46}
47run().catch(console.dir);

前の例を実行すると、次の出力が表示されます。

{ title: '10 Minutes', imdb: { rating: 7.9, votes: 743, id: 339976 } }
{ title: '3x3', imdb: { rating: 6.9, votes: 206, id: 1654725 } }
{ title: '7:35 in the Morning', imdb: { rating: 7.3, votes: 1555, id: 406501 } }
{ title: '8', imdb: { rating: 7.8, votes: 883, id: 1592502 } }
...

sort オプションと projection オプションは、find() メソッドに連結されたメソッド(sort()project())として指定することもできます。次の 2 つのコマンドは同等です。

movies.find({ runtime: { $lt: 15 } }, { sort: { title: 1 }, projection: { _id: 0, title: 1, imdb: 1 }});
movies.find({ runtime: { $lt: 15 } }).sort({ title: 1}).project({ _id: 0, title: 1, imdb: 1 });

戻る

ドキュメントの検索