Docs Menu
Docs Home
/ / /
Rust 드라이버
/

고유 필드 값 나열

인스턴스 에서distinct() 메서드를 호출하여 컬렉션 에 있는 문서 필드 의 고유 값을 나열할 수 있습니다.Collection 예를 예시 컬렉션 의 문서에 date 필드 가 포함된 경우 distinct() 메서드를 사용하여 컬렉션 에서 해당 필드 에 사용할 수 있는 모든 값을 찾을 수 있습니다.

필드 이름을 distinct() 메서드에 매개 변수로 전달하여 해당 필드 에 대한 고유 값을 반환합니다. 쿼리 필터하다 를 매개 변수로 전달하여 일치하는 문서의 하위 집합에서만 고유 필드 값을 찾을 수도 있습니다. 쿼리 필터 만들기에 학습 보려면 쿼리 지정 가이드 를 참조하세요.

메서드는 distinct() 고유 값 Vec<Bson> 목록을 의 BSON 벡터인 유형으로 반환합니다. 값.

이 예시 sample_restaurants 데이터베이스 의 restaurants 컬렉션 에서 필드 에 대한 고유 값을 찾습니다. distinct() 메서드는 cuisine 필드 값이 "Turkish"인 문서의 하위 집합에서 borough 필드 의 고유 값을 검색합니다.

restaurants 컬렉션 의 문서에 Document 유형 또는 사용자 지정 데이터 유형 의 인스턴스로 액세스 할 수 있습니다. 컬렉션의 데이터를 나타내는 데이터 유형 지정하려면 강조 표시된 줄의 <T> 유형 매개변수를 다음 값 중 하나로 바꿉니다.

  • <Document>: 컬렉션 문서를 BSON 문서로 나타냅니다.

  • <Restaurant>: 컬렉션 문서를 코드 상단에 정의된 Restaurant 구조체의 인스턴스로 나타냅니다.

Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.

use std::env;
use mongodb::{
bson::{ Document, doc },
Client,
Collection };
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
borough: String,
}
#[tokio::main]
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 filter = doc! { "cuisine": "Turkish" };
let boroughs = my_coll.distinct("borough", filter).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 }
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
borough: 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 filter = doc! { "cuisine": "Turkish" };
let boroughs = my_coll.distinct("borough", filter).run()?;
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")

돌아가기

Count