文档菜单
文档首页
/ / /
Java 反应式流驱动程序

聚合框架

本页内容

  • 先决条件
  • 连接到 MongoDB 部署
  • 执行聚合
  • 使用聚合表达式
  • 解释聚合

聚合管道是一个数据聚合框架,基于数据处理管道的概念。

要了解更多关于聚合的信息,请参阅聚合管道 服务器手册。

您必须设置以下组件才能运行本指南中的代码示例

  • Atest.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部署,然后声明并定义MongoDatabaseMongoCollection实例。

以下代码连接到在localhost27017端口上运行的独立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());

返回

索引