聚合框架
聚合管道是一个数据聚合框架,基于数据处理管道的概念。
要了解更多关于聚合的信息,请参阅聚合管道 服务器手册。
先决条件
您必须设置以下组件才能运行本指南中的代码示例
A
test.restaurants
集合,其中包含来自restaurants.json
文件的文档,该文件位于文档资源 GitHub。以下导入语句
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
实现,这些实现在本指南中描述。示例自定义 Subscriber 实现 指南。
连接到 MongoDB 部署
首先,连接到MongoDB部署,然后声明并定义MongoDatabase
和MongoCollection
实例。
以下代码连接到在localhost
的27017
端口上运行的独立MongoDB部署。然后,它定义了database
变量以引用test
数据库,以及collection
变量以引用restaurants
集合。
MongoClient mongoClient = MongoClients.create(); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("restaurants");
要了解更多关于连接到MongoDB部署的信息,请参阅连接到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
字段以及计算字段 firstCategory
,其值为 categories
数组中的第一个元素。示例使用 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());