ドキュメントをカウント
Node.js ドライバーでは、コレクション内のドキュメントをカウントするための 2 つの方法が提供されています。
collection.countDocuments() は、コレクション内の指定されたクエリに一致するドキュメントの数を返します。空のクエリ ドキュメントを指定すると、
countDocuments()
はコレクション内のドキュメントの総数を返します。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 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 const database = client.db("sample_mflix"); 11 const movies = database.collection("movies"); 12 13 // Estimate the total number of documents in the collection 14 // and print out the count. 15 const estimate = await movies.estimatedDocumentCount(); 16 console.log(`Estimated number of documents in the movies collection: ${estimate}`); 17 18 // Query for movies from Canada. 19 const query = { countries: "Canada" }; 20 21 // Find the number of documents that match the specified 22 // query, (i.e. with "Canada" as a value in the "countries" field) 23 // and print out the count. 24 const countCanada = await movies.countDocuments(query); 25 console.log(`Number of movies from Canada: ${countCanada}`); 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 async function run() { 9 try { 10 const database = client.db("sample_mflix"); 11 const movies = database.collection("movies"); 12 13 // Estimate the total number of documents in the collection 14 // and print out the count. 15 const estimate = await movies.estimatedDocumentCount(); 16 console.log(`Estimated number of documents in the movies collection: ${estimate}`); 17 18 // Query for movies from Canada. 19 const query = { countries: "Canada" }; 20 21 // Find the number of documents that match the specified 22 // query, (i.e. with "Canada" as a value in the "countries" field) 23 // and print out the count. 24 const countCanada = await movies.countDocuments(query); 25 console.log(`Number of movies from Canada: ${countCanada}`); 26 } finally { 27 await client.close(); 28 } 29 } 30 run().catch(console.dir);
注意
同一のコードスニペット
上記の JavaScript と TypeScript のコード スニペットは同一です。このユースケースに関連するドライバーの TypeScript 固有の機能はありません。
上記のサンプルコードを実行すると、次のような出力が表示されます。
Estimated number of documents in the movies collection: 23541 Number of movies from Canada: 1349