SQL의 Group by 분석과 유사하게 MongoDB도 지원합니다. 이 장에서는 Golang을 사용하여 MongoDB 데이터의 통계 분석을 구현하는 방법을 소개합니다.

선행 자습서

아래의 선행 자습서를 읽어주세요:

테스트 데이터

주문 컬렉션의 데이터는 다음과 같습니다:

{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }
{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }
{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }
{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }
{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }

그룹화 및 집계

Collection.Aggregate 함수를 사용하여 통계 쿼리를 수행합니다.

아래는 MongoDB에서 통계 분석의 예시입니다:

[
    { $match: { status: "A" } },  // 첫 번째 단계, 쿼리 조건에 따라 문서 데이터 일치시키기
    { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },   // 두 번째 단계, 그룹화 및 집계
    { $sort: { total: -1 } }  // 세 번째 단계, 결과 정렬
]

동등한 SQL 문:

select sum(amount) as total from orders 
        where status="A" 
        group by cust_id 
        order by total desc

Golang에서 동일한 작업을 수행하는 방법은 다음과 같습니다:

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	var coll *mongo.Collection
	
	// MongoDB에 연결하고 컬렉션 객체를 가져오는 코드는 여기서 생략되었으며 퀵 스타트 자습서를 참조하십시오.

	// Golang 데이터 구조를 사용하여 MongoDB 원시 구문을 표현하는 통계 분석 표현
	// Golang MongoDB 데이터 모델에 익숙하지 않은 경우, 이전 섹션을 참조하세요.
	pipeline := mongo.Pipeline{
			{{"$match", bson.D{{"status", "A"}}}},
			{{"$group", bson.D{{"_id", "$cust_id"}, {"total", bson.D{{"$sum", "$amount"}}}}}},
			{{"$sort", bson.D{{"total", -1}}}
	}
	
	// 타임아웃 설정
	opts := options.Aggregate().SetMaxTime(2 * time.Second)
	
	// 통계 분석 수행
	cursor, err := coll.Aggregate(
								context.TODO(),  // 컨텍스트 매개변수
								pipeline,  // 통계 분석 표현
								opts // 선택적 매개변수
							)
	if err != nil {
		log.Fatal(err)
	}

	// 결과 집합 정의, 쿼리 결과를 저장하기 위해 bson.M 타입 (맵 구조의 타입)을 사용합니다.
	var results []bson.M
	// 모든 결과를 가져와 결과 변수에 저장
	if err = cursor.All(context.TODO(), &results); err != nil {
		log.Fatal(err)
	}
	
	// 쿼리 결과 반복
	for _, result := range results {
		fmt.Printf("id =  %v , total =  %v \n", result["_id"], result["total"])
	}
}

팁: 더 많은 MongoDB 집계 구문은 MongoDB 집계 파이프라인을 참조하십시오.