コレクション内の複数のドキュメントをクエリするには、 インスタンスで find() Collectionメソッドを呼び出します。
コレクション内のフィルターに一致するドキュメントを返すには、 find()メソッドにクエリフィルターを渡します。 フィルターを含めない場合、MongoDB はコレクション内のすべてのドキュメントを返します。
find() メソッドはカーソル タイプを返します。これを反復処理して個々のドキュメントを取得できます。カーソルの使用の詳細については、カーソルを使用したデータへのアクセス ガイドを参照してください。
例
この例では、 sample_restaurantsデータベース内のrestaurantsコレクションからクエリフィルターに一致するドキュメントを検索します。 find() メソッドは、cuisineフィールドの値が "French" であるすべてのドキュメントを返します。
取得された各ドキュメントは、 Document タイプまたはカスタムデータ型としてモデル化できます。 コレクションのデータを表すデータ型を指定するには、強調表示された行の <T> 型パラメータを次のいずれかの値に置き換えます。
<Document>:コレクションドキュメントをBSONドキュメントとして検索して出力します<Restaurant>: コードの上部で定義されたRestaurant構造体のインスタンスとしてコレクションドキュメントを検索して出力します
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
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?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let mut cursor = my_coll.find( doc! { "cuisine": "French" } ).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)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let mut cursor = my_coll.find( doc! { "cuisine": "French" } ).run()?; for result in cursor { println!("{:#?}", result?); } Ok(()) }
出力
コレクションの型パラメータに基づいて対応するコード出力を表示するには、[BSON Document Results タブまたは Restaurant Struct Resultsタブを選択します。
... Some( Document({ "_id": ObjectId( "...", ), ... "name": String( "Cafe Un Deux Trois", ), ... }), ), Some( Document({ "_id": ObjectId( "...", ), ... "name": String( "Calliope", ), ... }), ) ...
... Restaurant { name: "Cafe Un Deux Trois", cuisine: "French", } Restaurant { name: "Calliope", cuisine: "French", } ...