Collection 인스턴스에서 distinct() 메서드를 호출하여 컬렉션에 있는 문서 필드의 고유 값을 나열할 수 있습니다. 예시 들어 컬렉션 의 문서에 date 필드 포함된 경우 distinct() 메서드를 사용하여 컬렉션 에서 해당 필드 에 사용할 수 있는 모든 값을 찾을 수 있습니다.
필드 이름을 distinct() 메서드에 매개변수로 전달하여 해당 필드에 대한 고유 값을 반환합니다. 쿼리 필터를 매개 변수로 전달하여 일치하는 문서의 하위 집합에서만 고유 필드 값을 찾을 수도 있습니다. 쿼리 필터 생성에 대해 자세히 알아보려면 쿼리 지정 가이드를 참조하세요.
distinct() 메서드는 고유 값 목록을 BSON 값의 벡터인 Vec<Bson> 유형으로 반환합니다.
예시
이 예에서는 sample_restaurants 데이터베이스의 restaurants collection에서 필드에 대한 고유 값을 찾습니다.
이 예에서는 cuisine 필드의 값이 "Turkish" 인 문서의 하위 집합에서 borough 필드의 고유 값을 찾습니다.
Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.
use std::env; use mongodb::{ bson::{ Document, doc }, Client, Collection }; async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; let my_coll: Collection<Document> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "cuisine": "Turkish" }; let boroughs = my_coll.distinct("borough", filter, None).await?; println!("List of field values for 'borough':"); for b in boroughs.iter() { println!("{:?}", b); } Ok(()) }
List of field values for 'borough': String("Brooklyn") String("Manhattan") String("Queens") String("Staten Island")
use std::env; use mongodb::{ bson::{ Document, doc }, sync::{ Client, Collection } }; fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; let my_coll: Collection<Document> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "cuisine": "Turkish" }; let boroughs = my_coll.distinct("borough", filter, None)?; println!("List of field values for 'borough':"); for b in boroughs.iter() { println!("{:?}", b); } Ok(()) }
List of field values for 'borough': String("Brooklyn") String("Manhattan") String("Queens") String("Staten Island")