Collectionインスタンスで次のいずれかのメソッドを呼び出すと、コレクション内のドキュメント数をカウントできます。
count_documents() : は、クエリフィルターに一致するドキュメントの数をカウントします。クエリフィルターの作成の詳細については、クエリの指定ガイドを参照してください。
Estimated_document_count() :コレクションメタデータを使用して、コレクション内のドキュメントの合計数を推定します。
各メソッドはカウントをu64インスタンスとして返します。
注意
count_documents()メソッドにフィルターを渡さない場合、MongoDB はコレクション内のドキュメントの総数をカウントします。
例
この例では、 sample_restaurantsデータベースの restaurantsコレクション内のドキュメントをカウントします。 この例では、 estimated_document_count() メソッドを使用して、コレクション内のドキュメントの合計数をカウントします。 次に、この例ではcount_documents() メソッドを使用して、nameフィールドの値に string "Sunset" が含まれるドキュメントの数をカウントします。
restaurantsコレクション内のドキュメントには、Document 型またはカスタムデータ型のインスタンスとしてアクセスできます。 コレクションのデータを表すデータ型を指定するには、強調表示された行の <T> 型パラメータを次のいずれかの値に置き換えます。
<Document>:コレクションドキュメントをBSONドキュメントとして表現します<Restaurant>: コードの上部で定義されたRestaurant構造体のインスタンスとしてコレクションドキュメントを表します
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
use std::env; use mongodb::{ bson::{ doc, Document }, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let ct = my_coll.estimated_document_count().await?; println!("Number of documents: {}", ct); let ct = my_coll.count_documents(doc! { "name": doc! { "$regex": "Sunset" } }).await?; println!("Number of matching documents: {}", ct); Ok(()) }
// Your values might differ Number of documents: 25216 Number of matching documents: 10
use std::env; use mongodb::{ bson::{ Document, doc }, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let ct = my_coll.estimated_document_count().run()?; println!("Number of documents: {}", ct); let ct = my_coll .count_documents(doc! { "name": doc! { "$regex": "Sunset" } }) .run()?; println!("Number of matching documents: {}", ct); Ok(()) }
// Your values might differ Number of documents: 25216 Number of matching documents: 10