Collectionインスタンスで find() メソッドを呼び出すと、コレクション内の複数のドキュメントをクエリできます。
コレクション内のフィルターに一致するドキュメントを返すには、 find()メソッドにクエリフィルターを渡します。 フィルターを含めない場合、MongoDB はコレクション内のすべてのドキュメントを返します。
find() メソッドはカーソル タイプを返します。これを反復処理して個々のドキュメントを取得できます。カーソルの使用の詳細については、カーソルを使用したデータへのアクセス ガイドを参照してください。
例
この例では、 sample_restaurantsデータベース内のrestaurantsコレクションからクエリフィルターに一致するドキュメントを検索します。 この例では、 Restaurant構造体のインスタンスに検索されたドキュメントのデータを入力します。
次のコードでは、 cuisineフィールドの値が"French"であるドキュメントに一致するクエリフィルターを使用します。
各実行時に対応するコードを表示するには、 AsynchronousタブまたはSynchronousタブを選択します。
use mongodb::{ bson::doc, Client, Collection};use futures::TryStreamExt;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?;
let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants");
let mut cursor = my_coll.find( doc! { "cuisine": "French" }, None ).await?;
while let Some(doc) = cursor.try_next().await? { println!("{:?}", doc); }
Ok(())}use mongodb::{ bson::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)?;
let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants");
let mut cursor = my_coll.find( doc! { "cuisine": "French" }, None )?; for result in cursor { println!("{:?}", result?); }
Ok(())}