Docs Menu

ドキュメントをカウント

このガイドでは、コレクション内のドキュメント数の正確な推定値を取得する方法を学習できます。

このガイドの例では、 Atlas サンプル データセットsample_mflixデータベースのmoviesコレクションを使用します。 MongoDB Atlas クラスターを無料で作成して、サンプル データセットをロードする方法については、 「 Atlas を使い始める 」ガイドを参照してください。

次の Kotlin データ クラスは、このコレクション内のドキュメントをモデル化します。

data class Movie(
@BsonId
val id: ObjectId,
val title: String
)

コレクション内のドキュメントの数をカウントするには、 countDocuments()メソッドを使用します。 指定した検索条件に一致するドキュメントの数をカウントするには、クエリフィルターをcountDocuments()メソッドに渡します。

クエリの指定の詳細については、「 クエリの指定 」を参照してください。

コレクション内のすべてのドキュメントの数を返すには、次の例に示すように、引数なしでcountDocuments()メソッドを呼び出します。

println(collection.countDocuments())
21349

特定の検索条件に一致するドキュメントの数を返すには、 countDocuments()メソッドでクエリを指定します。 次の例では、 moviesコレクション内のyearフィールド値が1930に等しいすべてのドキュメントのカウントを出力します。

println(collection.countDocuments(eq("year", "1930")))
10

countDocuments()メソッドは、カウント操作を構成するために使用できるオプションを表すCountOptionsオブジェクトの形式で任意のパラメータを受け入れます。 これらのオプションを設定するには、新しいCountOptionsオブジェクトをインスタンス化し、対応するメソッドを使用してオブジェクトのフィールドを設定し、それをcountDocuments()メソッドに渡します。 オプションを指定しない場合、ドライバーはカウント操作をカスタマイズしません。

次の表では、 countDocuments()をカスタマイズするために設定できるオプションについて説明しています。

オプション
説明

comment

Specifies a comment to attach to the operation.

skip

Sets the number of documents to skip before returning results.

limit

Sets the maximum number of documents to count. Must be a positive integer.

maxTime

Sets the maximum amount of time to allow the operation to run, in milliseconds.

collation

Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.

hint

Sets the index to scan for documents.

次の例では、 CountOptionsオブジェクトを使用してcountDocuments()操作にコメントを追加します。

val options = CountOptions().comment("Retrieving count")
collection.countDocuments(Filters.empty(), options)

コレクション内のドキュメント数の推定値を取得するには、 estimatedDocumentCount()メソッドを使用します。 メソッドはコレクション メタデータに基づいてドキュメントの量を推定します。これは正確なカウントを実行するよりも高速です。

次の例では、コレクション内のドキュメントの推定数を出力します。

print(collection.estimatedDocumentCount())
21349

estimatedDocumentCount()メソッドは、カウント操作を構成するために使用できるオプションを表すEstimatedDocumentCountOptionsオブジェクト の形式で任意のパラメータを受け入れます。 これらのオプションを設定するには、新しいEstimatedDocumentCountOptionsオブジェクトをインスタンス化し、対応するメソッドを使用してオブジェクトのフィールドを設定し、それをestimatedDocumentCount()メソッドに渡します。 オプションを指定しない場合、ドライバーはカウント操作をカスタマイズしません。

次の表では、 estimatedDocumentCount()をカスタマイズするために設定できるオプションについて説明しています。

オプション
説明

comment

Specifies a comment to attach to the operation.

maxTime

Specifies the maximum amount of time to allow the operation to run, in milliseconds.

次の例では、 EstimatedDocumentCountOptionsオブジェクトを使用してestimatedDocumentCount()操作にコメントを追加します。

val options = EstimatedDocumentCountOptions().comment("Retrieving count")
collection.estimatedDocumentCount(options)

このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。