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

집계

이 페이지의 내용

  • 개요
  • 비교 연산
  • 제한 사항
  • 예제
  • 추가 정보

이 가이드에서는 MongoDB Go 드라이버에서 애그리게이션 작업을 사용하는 방법을 배울 수 있습니다.

집계 작업은 aggregation pipeline의 사양에 따라 MongoDB 컬렉션의 데이터를 처리합니다. aggregation pipeline은 하나 이상의 단계로 구성됩니다. 각 단계는 해당 표현식 연산자를 기반으로 작업을 수행합니다. 드라이버가 aggregation pipeline을 실행한 후 집계된 결과를 반환합니다.

애그리게이션 작업은 자동차 공장과 유사하게 운영됩니다. 자동차 공장에는 조립 라인이 있습니다. 조립 라인에는 특정 작업을 수행하기 위한 특수 도구를 갖춘 조립 스테이션이 있습니다. 자동차를 만들려면 원부품을 공장으로 보내야 합니다. 그런 다음 조립 라인에서는 부품을 변형하여 자동차로 조립합니다.

조립 라인은 애그리게이션 파이프라인과 유사하고, 조립 라인의 조립 스테이션은 애그리게이션 단계와 유사합니다. 특수 도구는 표현식 연산자, 완제품은 애그리게이션 결과와 유사합니다.

다음 표에는 찾기 및 집계 작업으로 수행할 수 있는 작업이 나열되어 있습니다.

작업 찾기
집계 작업
Select what documents to return
Select which fields to return
Sort the results
Limit the results
Count the results
Select what documents to return
Select which fields to return
Sort the results
Limit the results
Count the results
Rename fields
Calculate fields
Summarize data
Group values

집계 작업에는 제한이 있습니다. 집계 작업을 수행할 때는 다음 사항에 유의해야 합니다.

  • 반환된 문서는 BSON 문서 크기 제한인 16메가바이트를 초과하지 않아야 합니다.

  • 파이프라인 단계의 메모리 제한은 기본적으로 100MB입니다. 필요한 경우 allowDiskUse 메서드를 사용하여 이 제한을 초과할 수 있습니다.

  • $graphLookup 단계에는 100 메가바이트의 엄격한 메모리 제한이 있으며 allowDiskUse 을(를) 무시합니다.

이 섹션의 예제에서는 다음 Tea 구조체를 tea 컬렉션에 있는 문서의 모델로 사용합니다.

type Tea struct {
Type string
Category string
Toppings []string
Price float32
}

이 섹션의 예시를 실행하려면 다음 스니펫을 사용하여 샘플 데이터를 db 데이터베이스의 tea 컬렉션에 로드합니다.

coll := client.Database("db").Collection("tea")
docs := []interface{}{
Tea{Type: "Masala", Category: "black", Toppings: []string{"ginger", "pumpkin spice", "cinnamon"}, Price: 6.75},
Tea{Type: "Gyokuro", Category: "green", Toppings: []string{"berries", "milk foam"}, Price: 5.65},
Tea{Type: "English Breakfast", Category: "black", Toppings: []string{"whipped cream", "honey"}, Price: 5.75},
Tea{Type: "Sencha", Category: "green", Toppings: []string{"lemon", "whipped cream"}, Price: 5.15},
Tea{Type: "Assam", Category: "black", Toppings: []string{"milk foam", "honey", "berries"}, Price: 5.65},
Tea{Type: "Matcha", Category: "green", Toppings: []string{"whipped cream", "honey"}, Price: 6.45},
Tea{Type: "Earl Grey", Category: "black", Toppings: []string{"milk foam", "pumpkin spice"}, Price: 6.15},
Tea{Type: "Hojicha", Category: "green", Toppings: []string{"lemon", "ginger", "milk foam"}, Price: 5.55},
}
result, err := coll.InsertMany(context.TODO(), docs)

각 문서에는 차 종류, 사용 가능한 토핑 및 가격에 대한 정보가 포함되어 있습니다.

다음 예에서는 각 차 카테고리에 대한 평균 평점과 평점 수를 계산하고 표시합니다.

aggregation pipeline은 $group 단계를 사용하여 category 필드별로 문서를 그룹화하고, $avg 표현식 연산자를 사용하여 평균을 계산하고, $sum 표현식 연산자를 사용하여 문서 수를 계산합니다.

// create group stage
groupStage := bson.D{
{"$group", bson.D{
{"_id", "$category"},
{"average_price", bson.D{{"$avg", "$price"}}},
{"type_total", bson.D{{"$sum", 1}}},
}}}
// pass the pipeline to the Aggregate() method
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{groupStage})
if err != nil {
panic(err)
}
// display the results
var results []bson.M
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Printf("Average price of %v tea options: $%v \n", result["_id"], result["average_price"])
fmt.Printf("Number of %v tea options: %v \n\n", result["_id"], result["type_total"])
}

다음 예는 topping으로 우유 거품을 넣을 수 있는 문서를 일치시키고 가장 저렴한 두 가지 옵션을 나열합니다.

애그리게이션 파이프라인에는 다음 단계가 포함됩니다:

  • $match '우유 거품'을 포함하는 toppings 필드가 있는 문서를 일치하는 단계

  • $unset _idcategory 필드를 생략하는 단계

  • $sort 단계를 사용하여 pricetoppings를 오름차순으로 정렬합니다.

  • $limit 처음 두 문서를 표시하는 단계

// create the stages
matchStage := bson.D{{"$match", bson.D{{"toppings", "milk foam"}}}}
unsetStage := bson.D{{"$unset", bson.A{"_id", "category"}}}
sortStage := bson.D{{"$sort", bson.D{{"price", 1}, {"toppings", 1}}}}
limitStage := bson.D{{"$limit", 2}}
// pass the pipeline to the Aggregate() method
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, unsetStage, sortStage, limitStage})
if err != nil {
panic(err)
}
// display the results
var results []Tea
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Printf("Tea: %v \nToppings: %v \nPrice: $%v \n\n", result.Type, strings.Join(result.Toppings, ", "), result.Price)
}

언급된 텀에 대해 자세히 알아보려면 다음 가이드를 참조하세요.

더 많은 애그리게이션 예시를 보려면 다음 가이드를 참조하세요:

  • Count

  • Limit

  • Skip

  • Text

Aggregate() 메서드 및 동작에 대해 자세히 알아보려면 데이터 검색을 참조하세요.

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

돌아가기

CRUD 작업 실행 수정하기