Collection 인스턴스에서 find_one() 메서드를 호출하여 컬렉션에서 단일 문서를 조회할 수 있습니다.
Pass a query filter to the find_one() method to return one document in the collection that matches the filter. If multiple documents match the query filter, this method returns the first matching document according to their natural order in the database or according to the sort order specified in a FindOneOptions instance.
find_one() 메서드는 Option<T> 유형을 반환하며, 여기서 T 는 인스턴스 매개변수화한 Collection 유형입니다.
문서 조회에 대한 자세한 내용은 데이터 조회 가이드를 참조하세요.
예시
이 예에서는 sample_restaurants 데이터베이스의 restaurants collection에서 쿼리 필터와 일치하는 문서를 조회합니다. 이 예제에서는 조회된 문서의 데이터로 Restaurant 구조체를 채웁니다.
이 예에서는 name 필드의 값이 "Tompkins Square Bagels" 인 문서와 일치하는 쿼리 필터를 사용합니다. MongoDB는 쿼리 필터와 일치하는 첫 번째 문서를 조회합니다.
Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.
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?; 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(()) }
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 result = my_coll.find_one( doc! { "name": "Tompkins Square Bagels" }, None )?; println!("{:#?}", result); Ok(()) }