Overview
このガイドでは、 MongoDBコレクション内のドキュメントの数をカウントする方法を学習できます。MongoCollection
クラスには、コレクション内のドキュメント数をカウントするために呼び出すことができる 2 つのインスタンスメソッドがあります。
countDocuments()
は、指定されたクエリに一致するコレクション内のドキュメントの数を返します。 空のクエリフィルターを指定すると、メソッドはコレクション内のドキュメントの総数を返します。estimatedDocumentCount()
は、コレクションのメタデータに基づいて、コレクション内のドキュメントの数の推定値を返します。 このメソッドを使用する場合、クエリを指定することはできません。
estimatedDocumentCount()
メソッドは、コレクション全体をスキャンするのではなく、コレクションのメタデータを使用するため、 countDocuments()
メソッドよりも速く返します。 countDocuments()
メソッドはドキュメントの数の正確なカウントを返し、フィルターの指定をサポートします。
Tip
countDocuments()
を使用してコレクション内のドキュメントの合計数を返す場合、コレクションスキャンを回避してパフォーマンスを向上できます。 そのためには、 ヒントを使用して_id
フィールドの組み込みインデックスを活用します。 この手法は、空のクエリ パラメータを使用してcountDocuments()
を呼び出す場合にのみ使用してください。
CountOptions opts = new CountOptions().hintString("_id_"); long numDocuments = collection.countDocuments(new BsonDocument(), opts);
countDocuments()
メソッドを呼び出すときは、任意でクエリフィルターパラメータを渡すことができます。 estimatedDocumentCount()
を呼び出すときにパラメータを渡すことはできません。
重要
Stable API V1 と MongoDB Server の問題
Stable API V1
estimatedDocumentCount()
「strict」オプションとともに使用し、かつ MongoDB Server バージョン 5.0.0 から 5.0.8 までの場合、サーバーのバグによりエラーが発生する可能性があります。
この問題を回避するには、MongoDB Server 5.0.9 にアップグレードするか、Stable API の「strict」オプションをfalse
に設定します。
これらのメソッドのいずれかに任意のパラメーターを渡して、呼び出しの動作を指定することもできます。
方式 | 任意のパラメーター クラス | 説明 |
---|---|---|
|
| カウントするドキュメントの最大数を指定するには |
|
|
|
どちらの方法も、一致するドキュメントの数をlong
プリミティブとして返します。
ドキュメントをカウントする例:完全なファイル
注意
セットアップ例
この例では、接続 URI を使用してMongoDBのインスタンスに接続します。MongoDBインスタンスへの接続の詳細については、「 MongoClient の作成ガイド 」を参照してください。この例では、Atlasサンプルデータセットに含まれる sample_mflix
データベースの movies
コレクションも使用します。「Atlas を使い始める」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。
次の例では、sample_mflix
データベース内の movies
コレクション内のドキュメントの数が推定され、その後movies
コレクション内のcountries
フィールドに Canada
が含まれるドキュメントの正確な数が返されます。
/** * This file demonstrates how to open a change stream by using the Java driver. * It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens * to change events in the "movies" collection. The code uses a change stream with a pipeline * to only filter for "insert" and "update" events. */ package usage.examples; import static com.mongodb.client.model.Filters.eq; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class CountDocuments { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); Bson query = eq("countries", "Spain"); // Retrieves and prints the estimated number of documents in the collection long estimatedCount = collection.estimatedDocumentCount(); System.out.println("Estimated number of documents in the movies collection: " + estimatedCount); // Retrieves and prints the number of documents with a "countries" value of "Spain" long matchingCount = collection.countDocuments(query); System.out.println("Number of movies from Spain: " + matchingCount); } } }
上記のサンプル コードを実行すると、次のような出力が表示されます(正確な数値はデータによって異なる場合があります)。
Estimated number of documents in the movies collection: 23541 Number of movies from Spain: 755
詳細情報
API ドキュメント
ドキュメントをカウントするために使用されるクラスとメソッドの詳細については、次のAPIドキュメントを参照してください。