Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Rust ドライバー
/

ドキュメントの検索

コレクションから単一ドキュメントを検索するには、 インスタンスで find_one() Collectionメソッドを呼び出します。

クエリフィルターをfind_one()メソッドに渡すと、コレクション内でフィルターに一致する 1 つのドキュメントが返されます。 複数のドキュメントがクエリフィルターに一致する場合、このメソッドはデータベース内の自然な順序に従って、またはFindOneOptionsインスタンスに指定されたソート順序に従って最初に一致するドキュメントを返します。

find_one()メソッドは Option<T> TCollectionタイプを返します。ここで、 は インスタンスをパラメータ化したタイプです。

ドキュメントの取得の詳細については、「 データの取得」ガイドを参照してください。

この例では、 sample_restaurantsデータベース内のrestaurantsコレクションからクエリフィルターに一致するドキュメントを検索します。 この例では、検索されたドキュメントのデータをRestaurant構造体に入力します。

この例では、 nameフィールドの値が"Tompkins Square Bagels"であるドキュメントに一致するクエリフィルターを使用します。 MongoDB は、クエリフィルターに一致する最初のドキュメントを検索します。

AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。

use mongodb::{
bson::doc,
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
#[tokio::main]
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 result = my_coll.find_one(
doc! { "name": "Tompkins Square Bagels" },
None
).await?;
println!("{:#?}", result);
Ok(())
}
Some(
Restaurant {
name: "Tompkins Square Bagels",
cuisine: "American",
},
)
use mongodb::{
bson::doc,
sync::{Client, Collection}
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
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 result = my_coll.find_one(
doc! { "name": "Tompkins Square Bagels" },
None
)?;
println!("{:#?}", result);
Ok(())
}
Some(
Restaurant {
name: "Tompkins Square Bagels",
cuisine: "American",
},
)

戻る

CRUD の例