집계 파이프라인은 데이터 처리 파이프라인 개념을 모델로 한 데이터 애그리게이션 프레임워크입니다.
집계 에 학습 보려면 서버 매뉴얼에서 집계 파이프라인 을 참조하세요.
전제 조건
이 가이드의 코드 예제를 실행하려면 다음 구성 요소를 설정해야 합니다.
test.restaurants문서 자산restaurants.jsonGithub 에 있는 파일의 문서로 채워진 컬렉션 입니다.다음 가져오기 문:
import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoCollection; import com.mongodb.reactivestreams.client.MongoDatabase; import com.mongodb.client.model.Aggregates; import com.mongodb.client.model.Accumulators; import com.mongodb.client.model.Projections; import com.mongodb.client.model.Filters; import org.bson.Document;
중요
이 가이드 에서는 샘플 사용자 지정 구독자 구현 가이드 에 설명된 사용자 지정 Subscriber 구현을 사용합니다.
MongoDB 배포에 연결하기
먼저 MongoDB deployment에 연결한 다음 MongoDatabase 및 MongoCollection 인스턴스를 선언하고 정의합니다.
다음 코드는 포트 27017 의 localhost 에서 실행되는 독립형 MongoDB 배포서버에 연결합니다. 그런 다음 test 데이터베이스를 참조하는 database 변수와 restaurants 컬렉션을 참조하는 collection 변수를 정의합니다.
MongoClient mongoClient = MongoClients.create(); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("restaurants");
MongoDB deployment에 연결하는 방법에 대해 자세히 알아보려면 MongoDB에 연결 튜토리얼을 참조하세요.
집계 수행
집계 집계 단계 목록을 MongoCollection.aggregate() 메서드에 전달합니다. 이 운전자 는 집계 단계에 대한 빌더 가 포함된 Aggregates 헬퍼 클래스를 제공합니다.
이 예제에서 집계 파이프라인은 다음 작업을 수행합니다.
$match단계를 사용하여categories배열 필드에"Bakery"요소가 포함된 문서를 필터링합니다. 이 예제에서는Aggregates.match()를 사용하여$match단계를 빌드합니다.
$group단계를 사용하여 일치하는 문서를stars필드 별로 그룹 하여stars의 각 고유 값에 대한 문서 수를 누적합니다. 이 예시 에서는Aggregates.group()를 사용하여$group단계를 빌드 하고Accumulators.sum()를 사용하여 축적자 표현식 을 빌드 합니다.$group단계 내에서 사용하기 위한 축적자 자 표현식의 경우 운전자 는Accumulators헬퍼 클래스를 제공합니다.
collection.aggregate( Arrays.asList( Aggregates.match(Filters.eq("categories", "Bakery")), Aggregates.group("$stars", Accumulators.sum("count", 1)) ) ).subscribe(new PrintDocumentSubscriber());
애그리게이션 표현식 사용
$group 축적자 자 표현식의 경우 운전자 는 Accumulators 헬퍼 클래스를 제공합니다. 다른 집계 표현식의 경우 Document 클래스를 사용하여 표현식 을 수동으로 빌드 합니다.
다음 예제에서 집계 파이프라인은 $project 단계를 사용하여 name 필드와 값이 categories 배열의 첫 번째 요소인 계산된 필드 firstCategory 만 반환합니다. 이 예제에서는 Aggregates.project() 및 다양한 Projections 클래스 메서드를 사용하여 $project 단계를 빌드합니다.
collection.aggregate( Arrays.asList( Aggregates.project( Projections.fields( Projections.excludeId(), Projections.include("name"), Projections.computed( "firstCategory", new Document("$arrayElemAt", Arrays.asList("$categories", 0)) ) ) ) ) ).subscribe(new PrintDocumentSubscriber());
애그리게이션 설명
집계 파이프라인 을 $explain 하려면 AggregatePublisher.explain() 메서드를 호출합니다.
collection.aggregate( Arrays.asList( Aggregates.match(Filters.eq("categories", "Bakery")), Aggregates.group("$stars", Accumulators.sum("count", 1)))) .explain() .subscribe(new PrintDocumentSubscriber());