コレクションから単一ドキュメントを検索するには、 Collectionインスタンスで find_one() メソッドを呼び出します。
クエリフィルターをfind_one()メソッドに渡すと、コレクション内でフィルターに一致する 1 つのドキュメントが返されます。 複数のドキュメントがクエリフィルターに一致する場合、このメソッドはデータベース内の自然な順序に従って、またはFindOneOptionsインスタンスに指定されたソート順序に従って最初に一致するドキュメントを返します。
find_one() メソッドは Option<T> タイプを返します。ここで、T は Collectionインスタンスをパラメータ化したタイプです。
ドキュメントの取得の詳細については、「 データの取得」ガイドを参照してください。
例
この例では、 sample_restaurantsデータベース内の restaurantsコレクションからクエリフィルターに一致するドキュメントを検索します。 find_one() メソッドは、nameフィールドの値が "Tompkins Square Bagels" である最初のドキュメントを返します。
取得されたドキュメントは、 Document 型またはカスタムデータ型としてモデル化できます。 コレクションのデータを表すデータ型を指定するには、強調表示された行の <T> 型パラメータを次のいずれかの値に置き換えます。
<Document>:コレクションドキュメントをBSONドキュメントとして検索して出力します<Restaurant>: コードの上部で定義されたRestaurant構造体のインスタンスとしてコレクションドキュメントを検索して出力します
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
use mongodb::{ bson::doc, 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 result = my_coll.find_one( doc! { "name": "Tompkins Square Bagels" } ).await?; println!("{:#?}", result); 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 result = my_coll.find_one( doc! { "name": "Tompkins Square Bagels" } ).run()?; println!("{:#?}", result); Ok(()) }
出力
コレクションの型パラメータに基づいて対応するコード出力を表示するには、[BSON Document Result タブまたは Restaurant Struct Resultタブを選択します。
Some( Document({ "_id": ObjectId( "...", ), ... "name": String( "Tompkins Square Bagels", ), ... }), )
Some( Restaurant { name: "Tompkins Square Bagels", cuisine: "American", }, )