Collection 인스턴스 에서 find_one() 메서드를 호출하여 컬렉션 에서 단일 문서 조회 할 수 있습니다.
쿼리 필터를 find_one() 메서드에 전달하여 컬렉션에서 필터와 일치하는 문서 하나를 반환합니다. 여러 문서가 쿼리 필터와 일치하는 경우 이 메서드는 데이터베이스의 기본 순서 또는 FindOneOptions 인스턴스에 지정된 정렬 순서에 따라 첫 번째로 일치하는 문서를 반환합니다.
find_one() 메서드는 Option<T> 유형을 반환하며, 여기서 T 는 인스턴스 매개변수화한 Collection 유형입니다.
문서 검색에 학습 보려면 데이터 검색 가이드 를 참조하세요.
예시
이 예시 sample_restaurants 데이터베이스 의 restaurants 컬렉션 에서 쿼리 필터하다 와 일치하는 문서 조회합니다. find_one() 메서드는 name 필드 의 값이 "Tompkins Square Bagels"인 첫 번째 문서 반환합니다.
조회된 문서 Document 유형 또는 사용자 지정 데이터 유형 으로 모델링할 수 있습니다. 컬렉션의 데이터를 나타내는 데이터 유형 지정하려면 강조 표시된 줄의 <T> 유형 매개변수를 다음 값 중 하나로 바꿉니다.
- <Document>: 컬렉션 문서를 BSON 문서로 조회하고 인쇄합니다.
- <Restaurant>: 코드 상단에 정의된- Restaurant구조체의 인스턴스로 컬렉션 문서를 조회하고 인쇄합니다.
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?;     // 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",    }, )