Overview
このガイドでは、 MongoDBコレクション内のドキュメントの数をカウントする方法を学習できます。Node.jsドライバーでは、 コレクション内のドキュメントをカウントするための 2 つの方法が提供されています。
collection.countDocuments() returns the number of documents in the collection that match the specified query. If you specify an empty query document,
countDocuments()returns the total number of documents in the collection.コレクション .estimatedDocumentCount() は、コレクションのメタデータに基づいて、コレクション内のドキュメント数の推定値を返します。
estimatedDocumentCount() この推定では、コレクションをスキャンする代わりにコレクションのメタデータが使用されるため、countDocuments() よりも高速です。対照的に、 countDocuments()は結果が返されるまでに時間がかかりますが、ドキュメントの数を正確にカウントし、フィルターの指定もサポートされています。ワークロードに適した方法を選択します。
カウントするドキュメントを指定するには、 countDocuments()でクエリパラメータを使用します。countDocuments()では指定されたクエリに一致するドキュメントがカウントされます。
countDocuments() estimatedDocumentCount()は、メソッドの実行に影響するオプションの設定をサポートします。詳細については、各メソッドの参考ドキュメントを参照してください。
Tip
You can improve performance when using countDocuments() to return the total number of documents in a collection by avoiding a collection scan. To do this, use a hint to take advantage of the built-in index on the _id field. Use this technique only when calling countDocuments() with an empty query parameter.
collection.countDocuments({}).hint("_id");
countDocuments() の例: 完全なファイル
注意
セットアップ例
この例では、接続 URI を使用してMongoDBのインスタンスに接続します。MongoDBインスタンスへの接続の詳細については、MongoDBへの接続ガイドを参照してください。この例では、Atlasサンプルデータセットに含まれる sample_mflixデータベースの moviesコレクションも使用します。MongoDB の使用開始に従って、 MongoDB Atlasの無料階層のデータベースにロードできます。
注意
Typescript固有の機能はありません
次のコード例ではJavaScriptを使用します。このユースケースに関連するドライバーのTypescript固有の機能はありません。
次の例では、sample_mflixデータベース内の moviesコレクション内のドキュメント数を推定し、countriesフィールドに Canada が含まれる moviesコレクション内のドキュメント数の正確なカウントを返します。
1 // Count documents in a collection 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 /* Print the estimate of the number of documents in the 16 "movies" collection */ 17 const estimate = await movies.estimatedDocumentCount(); 18 console.log(`Estimated number of documents in the movies collection: ${estimate}`); 19 20 /* Print the number of documents in the "movies" collection that 21 match the specified query */ 22 const query = { countries: "Canada" }; 23 const countCanada = await movies.countDocuments(query); 24 console.log(`Number of movies from Canada: ${countCanada}`); 25 } finally { 26 // Close the connection after the operations complete 27 await client.close(); 28 } 29 } 30 // Run the program and print any thrown exceptions 31 run().catch(console.dir);
上記のサンプルコードを実行すると、次の出力が得られます。
Estimated number of documents in the movies collection: 23541 Number of movies from Canada: 1349
API ドキュメント
このガイドで説明した型やメソッドの詳細については、次の API ドキュメントを参照してください。