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
countDocuments()
を使用してコレクション内のドキュメントの合計数を返すと、コレクションスキャンを回避してパフォーマンスを向上させることができます。 そのためには、ヒントを使用して_id
フィールドの組み込みインデックスを活用してください。 この手法は、空のクエリ パラメータを使用してcountDocuments()
を呼び出す場合にのみ使用してください。
collection.countDocuments({}, { hint: "_id_" });
例
次の例では、sample_mflix
データベース内の movies
コレクション内のドキュメントの数が推定され、その後movies
コレクション内のcountries
フィールドに Canada
が含まれるドキュメントの正確な数が返されます。
注意
この例を使って MongoDB のインスタンスに接続し、サンプルデータを含むデータベースとやり取りできます。MongoDB インスタンスへの接続とサンプル データセットの読み込みの詳細については、使用例ガイドを参照してください。
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);
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);
注意
同一のコードスニペット
上記の JavaScript と TypeScript のコード スニペットは同一です。このユースケースに関連するドライバーの TypeScript 固有の機能はありません。
上記のサンプルコードを実行すると、次のような出力が表示されます。
Estimated number of documents in the movies collection: 23541 Number of movies from Canada: 1349