Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Go 드라이버
/ /

Retrieve Distinct Values

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

이 가이드의 예시에서는 다음 Course 구조체를 courses 컬렉션의 문서 모델로 사용합니다.

type Course struct {
Title string
Department string
Enrollment int32
}

예제를 실행하려면 다음 스니펫을 사용하여 샘플 데이터를 db.courses collection에 로드합니다.

coll := client.Database("db").Collection("courses")
docs := []interface{}{
Course{Title: "World Fiction", Department: "English", Enrollment: 35},
Course{Title: "Abstract Algebra", Department: "Mathematics", Enrollment: 60},
Course{Title: "Modern Poetry", Department: "English", Enrollment: 12},
Course{Title: "Plate Tectonics", Department: "Geology", Enrollment: 30},
}
result, err := coll.InsertMany(context.TODO(), docs)

존재하지 않는 데이터베이스 및 collection

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

각 문서에는 과정 제목, 부서 및 등록을 포함하는 대학 과정에 대한 설명이 포함되어 있습니다. 이러한 항목은 각 문서의 title, departmentenrollment 필드에 해당합니다.

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

  • 고유 값을 조회 하려는 필드 이름

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

빈 쿼리 필터를 지정하면 Distinct() 메서드는 collection의 모든 문서에서 고유 값을 검색합니다.

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

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

메서드
설명

SetCollation()

The type of language collation to use when sorting results.
Default: nil

SetComment()

Sets a comment to attach to the distinct operation.
Default: nil

다음 예시 enrollment 필드 값이 50 보다 작은 문서를 일치시키고 Distinct() 메서드를 사용하여 department 필드 의 고유 값을 출력합니다.

filter := bson.D{{"enrollment", bson.D{{"$lt", 50}}}}
var arr []string
err = coll.Distinct(context.TODO(), "department", filter).Decode(&arr)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", arr)
[English Geology]

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_restaurants 데이터베이스의 restaurants 컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

이 예시에서는 restaurant 컬렉션에서 다음 조치를 수행합니다.

  • cuisine 필드 값이 "Tapas"인 문서와 일치합니다.

  • 일치하는 문서에서 borough 필드 의 고유 값을 반환합니다.

// Retrieves distinct values of a field by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
type Restaurant struct {
ID bson.ObjectID `bson:"_id"`
Name string
RestaurantId string `bson:"restaurant_id"`
Cuisine string
Address interface{}
Borough string
Grades interface{}
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ko-kr/docs/drivers/go/current/usage-examples/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
// Filters the collection for documents where the value of cuisine is "Tapas"
coll := client.Database("sample_restaurants").Collection("restaurants")
filter := bson.D{{"cuisine", "Tapas"}}
// Retrieves the distinct values of the "borough" field in documents
// that match the filter
var arr []string
err = coll.Distinct(context.TODO(), "borough", filter).Decode(&arr)
if err != nil {
panic(err)
}
// Prints the distinct "borough" values
for _, result := range arr {
fmt.Println(result)
}
// When you run this file, it should print:
// Brooklyn
// Manhattan
// Queens
}
Brooklyn
Manhattan
Queens

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

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

돌아가기

문서 수 계산

이 페이지의 내용