Retrieve Distinct Values — Go
Docs Menu

Docs HomeGo

Retrieve Distinct Values

이 가이드에서는 단일 collection에서 지정된 필드에 대한 고유 값을 검색하는 방법을 배울 수 있습니다.

이 가이드의 예시를 실행하려면 다음 스니펫을 사용하여 샘플 데이터를 tea.ratings collection에 로드하세요.

coll := client.Database("tea").Collection("ratings")
docs := []interface{}{
bson.D{{"type", "Masala"}, {"rating", 10}},
bson.D{{"type", "Matcha"}, {"rating", 7}},
bson.D{{"type", "Masala"}, {"rating", 4}},
bson.D{{"type", "Oolong"}, {"rating", 9}},
bson.D{{"type", "Matcha"}, {"rating", 5}},
bson.D{{"type", "Earl Grey"}, {"rating", 8}},
bson.D{{"type", "Oolong"}, {"rating", 3}},
bson.D{{"type", "Matcha"}, {"rating", 6}},
bson.D{{"type", "Earl Grey"}, {"rating", 4}},
}
result, err := coll.InsertMany(context.TODO(), docs)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))

존재하지 않는 데이터베이스 및 컬렉션

쓰기 작업을 수행할 때 필요한 데이터베이스 및 collection이 없는 경우 서버는 이를 암시적으로 생성합니다.

각 문서 에는 typerating 필드에 해당하는 차 유형에 대한 평점이 포함되어 있습니다.

단일 collection에서 지정된 필드의 고유 값을 검색하려면 다음 매개 변수를 Distinct() 메서드에 전달합니다.

  • 고유 값을 원하는 필드 이름

  • 일치시킬 문서를 지정하는 non-nil 쿼리 필터

If you specify an empty query filter, the method matches all the documents in a collection.

DistinctOptions를 전달하여 Distinct() 메서드의 동작을 수정할 수 있습니다. DistinctOptions를 지정하지 않으면 드라이버는 각 옵션의 기본값을 사용합니다.

DistinctOptions 유형을 사용하면 다음 방법으로 옵션을 구성할 수 있습니다.

메서드
설명
SetCollation()
The type of language collation to use when sorting results.
Default: nil
SetMaxTime()
The maximum amount of time that the query can run on the server.
Default: nil

The following example matches all documents and prints the distinct values of the type field using the Distinct() method:

results, err := coll.Distinct(context.TODO(), "type", bson.D{})
if err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}

고유 값 검색의 실행 가능한 예제 는 필드의 고유 값 검색을 참조하세요.

쿼리 필터 구성에 대해 알아보려면 쿼리 지정을 참조하세요.

이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

피드백 제공