|
此版本仍在开发中,尚未被视为稳定版。如需最新稳定版本,请使用 Spring Data MongoDB 5.0.4! |
聚合框架支持
Spring Data MongoDB 提供了对 MongoDB 2.2 版本中引入的聚合框架(Aggregation Framework)的支持。
如需更多信息,请参阅 MongoDB 聚合框架及其他数据聚合工具的完整参考文档。
基本概念
Spring Data MongoDB 中的聚合框架支持基于以下关键抽象:Aggregation 和 AggregationResults。
-
AggregationAggregation表示一个 MongoDBaggregate操作,并包含聚合管道指令的描述。通过调用newAggregation(…)类的相应Aggregation静态工厂方法来创建聚合操作,该方法接收一个AggregateOperation列表以及一个可选的输入类。实际的聚合操作由
aggregate的MongoTemplate方法执行,该方法将所需的输出类作为参数。 -
TypedAggregationTypedAggregation与Aggregation类似,包含聚合管道的指令以及对输入类型的引用,该引用用于将领域属性映射到实际的文档字段。在运行时,字段引用会根据给定的输入类型进行检查,并考虑可能存在的
@Field注解。
自 3.2 版本起,引用不存在的属性将不再引发错误。若要恢复之前的行为,请使用 strictMapping 的 AggregationOptions 选项。
-
AggregationDefinitionAggregationDefinition表示一个 MongoDB 聚合管道操作,并描述在此聚合步骤中应执行的处理。尽管您可以手动创建一个AggregationDefinition,但我们建议使用Aggregate类提供的静态工厂方法来构建AggregateOperation。 -
AggregationResultsAggregationResults是聚合操作结果的容器。它提供了对原始聚合结果的访问,该结果以Document的形式呈现,并包含映射后的对象以及有关聚合的其他信息。以下示例展示了使用 Spring Data MongoDB 对 MongoDB 聚合框架支持的标准用法:
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; Aggregation agg = newAggregation( pipelineOP1(), pipelineOP2(), pipelineOPn() ); AggregationResults<OutputType> results = mongoTemplate.aggregate(agg, "INPUT_COLLECTION_NAME", OutputType.class); List<OutputType> mappedResult = results.getMappedResults();
请注意,如果您将输入类作为第一个参数传递给 newAggregation 方法,MongoTemplate 会从该类推导出输入集合的名称。否则,如果您未指定输入类,则必须显式提供输入集合的名称。如果同时提供了输入类和输入集合,则后者优先。
支持的聚合操作与阶段
MongoDB 聚合框架提供了以下类型的聚合阶段和操作:
-
addFields -
AddFieldsOperation -
bucket / bucketAuto -
BucketOperation/BucketAutoOperation -
count -
CountOperation -
密集化 -
DensifyOperation -
facet -
FacetOperation -
geoNear -
GeoNearOperation -
groupLookup -
GraphLookupOperation -
group -
GroupOperation -
limit -
LimitOperation -
lookup -
LookupOperation -
匹配 -
MatchOperation -
合并 -
MergeOperation -
项目 -
ProjectionOperation -
脱敏 -
RedactOperation -
replaceRoot -
ReplaceRootOperation -
sample -
SampleOperation -
set -
SetOperation -
setWindowFields -
SetWindowFieldsOperation -
skip -
SkipOperation -
sort / sortByCount -
SortOperation/SortByCountOperation -
unionWith -
UnionWithOperation -
unset -
UnsetOperation -
未舒缓 -
UnwindOperation
|
不支持的聚合阶段(例如 MongoDB Atlas 的 $search)可以通过实现
|
截至本文撰写时,我们在 Spring Data MongoDB 中提供了对以下聚合操作符的支持:
集合聚合操作符 |
|
分组/累加器聚合操作符 |
|
算术聚合运算符 |
|
字符串聚合操作符 |
|
比较聚合操作符 |
|
数组聚合操作符 |
|
字面量运算符 |
|
日期聚合操作符 |
|
变量运算符 |
|
条件聚合操作符 |
|
类型聚合操作符 |
|
转换聚合操作符 |
|
对象聚合操作符 |
|
脚本聚合操作符 |
|
* 该操作由 Spring Data MongoDB 映射或添加。
请注意,此处未列出的聚合操作目前不受 Spring Data MongoDB 支持。比较类聚合操作符以 Criteria 表达式的形式表示。
投影表达式
投影表达式用于定义特定聚合步骤的结果字段。可以通过Aggregation类的project方法来定义这些投影表达式,既可以传递一个String对象列表,也可以通过聚合框架的Fields对象来定义。通过使用and(String)方法和as(String)方法,可以使用面向对象的方式扩展投影,并对其进行别名化。
请注意,你也可以通过使用聚合框架中的Fields.field静态工厂方法来定义带有别名的字段,然后使用这些字段构建一个新的Fields实例。在后续的聚合阶段中只能引用包含字段或其别名(包括新定义的字段及其别名)的字段名称。未包含在投影中的字段在后续的聚合阶段中无法被引用。以下示例展示了投影表达式的使用方法:
// generates {$project: {name: 1, netPrice: 1}}
project("name", "netPrice")
// generates {$project: {thing1: $thing2}}
project().and("thing1").as("thing2")
// generates {$project: {a: 1, b: 1, thing2: $thing1}}
project("a","b").and("thing1").as("thing2")
// generates {$project: {name: 1, netPrice: 1}}, {$sort: {name: 1}}
project("name", "netPrice"), sort(ASC, "name")
// generates {$project: {name: $firstname}}, {$sort: {name: 1}}
project().and("firstname").as("name"), sort(ASC, "name")
// does not work
project().and("firstname").as("name"), sort(ASC, "firstname")
更多关于投影操作的示例可以在 AggregationTests 类中找到。有关投影表达式的更多详细信息,请参阅 MongoDB 聚合框架参考文档中的相应章节。
分面分类
从 3.4 版本起,MongoDB 通过使用聚合框架(Aggregation Framework)支持分面分类(faceted classification)。分面分类采用语义类别(可以是通用的或特定主题的),这些类别组合起来形成完整的分类条目。在聚合管道中流动的文档会被归类到不同的桶(buckets)中。多分面分类允许对同一组输入文档执行多种聚合操作,而无需多次检索输入文档。
存储桶
桶操作(Bucket operations)根据指定的表达式和桶边界,将传入的文档划分为若干组,称为“桶”(buckets)。桶操作需要一个分组字段或分组表达式。您可以通过 bucket() 类的 bucketAuto() 和 Aggregate 方法来定义这些操作。BucketOperation 和 BucketAutoOperation 可以基于聚合表达式对输入文档进行累积计算。您可以使用流畅 API(fluent API),通过 with…() 方法和 andOutput(String) 方法为桶操作添加额外参数。此外,还可以使用 as(String) 方法为该操作设置别名。每个桶在输出中都表示为一个文档。
BucketOperation 使用一组定义好的边界将传入的文档分组到这些类别中。边界必须是有序的。以下示例展示了一些桶操作:
// generates {$bucket: {groupBy: $price, boundaries: [0, 100, 400]}}
bucket("price").withBoundaries(0, 100, 400);
// generates {$bucket: {groupBy: $price, default: "Other" boundaries: [0, 100]}}
bucket("price").withBoundaries(0, 100).withDefault("Other");
// generates {$bucket: {groupBy: $price, boundaries: [0, 100], output: { count: { $sum: 1}}}}
bucket("price").withBoundaries(0, 100).andOutputCount().as("count");
// generates {$bucket: {groupBy: $price, boundaries: [0, 100], 5, output: { titles: { $push: "$title"}}}
bucket("price").withBoundaries(0, 100).andOutput("title").push().as("titles");
BucketAutoOperation 用于确定边界,以尝试将文档均匀地分配到指定数量的桶中。BucketAutoOperation 可选择性地接受一个粒度(granularity)值,该值指定用于计算边界的优选数值序列,以确保计算出的边界落在优选的整数或10的幂上。以下列表展示了桶操作的示例:
// generates {$bucketAuto: {groupBy: $price, buckets: 5}}
bucketAuto("price", 5)
// generates {$bucketAuto: {groupBy: $price, buckets: 5, granularity: "E24"}}
bucketAuto("price", 5).withGranularity(Granularities.E24).withDefault("Other");
// generates {$bucketAuto: {groupBy: $price, buckets: 5, output: { titles: { $push: "$title"}}}
bucketAuto("price", 5).andOutput("title").push().as("titles");
要创建桶中的输出字段,桶操作可以通过 AggregationExpression 使用 andOutput() 方法,以及通过 #mongo.aggregation.projection.expressions 方法使用 SpEL 表达式。
请注意,有关桶表达式的更多详细信息,请参阅 MongoDB 聚合框架参考文档中的 $bucket 部分 和
$bucketAuto 部分。
多维聚合
可以使用多个聚合管道在一个聚合阶段内创建多维度(或多方面)的聚合,以从多个维度对数据进行刻画。多维度聚合提供多种过滤器和分类方式,用于引导数据的浏览与分析。实现多维度聚合的一个常见示例是,许多在线零售商通过在产品价格、制造商、尺寸及其他因素上应用过滤器,帮助用户缩小搜索结果范围。
你可以通过使用 FacetOperation 类的 facet() 方法来定义一个 Aggregation。你可以使用 and() 方法为其添加多个聚合管道。每个子管道在输出文档中都有其自己的字段,用于将其结果以文档数组的形式存储。
子管道可以在分组之前对输入文档进行投影和过滤。常见用例包括在分类前提取日期部分或进行计算。以下列表展示了 facet 操作的示例:
// generates {$facet: {categorizedByPrice: [ { $match: { price: {$exists : true}}}, { $bucketAuto: {groupBy: $price, buckets: 5}}]}}
facet(match(Criteria.where("price").exists(true)), bucketAuto("price", 5)).as("categorizedByPrice"))
// generates {$facet: {categorizedByCountry: [ { $match: { country: {$exists : true}}}, { $sortByCount: "$country"}]}}
facet(match(Criteria.where("country").exists(true)), sortByCount("country")).as("categorizedByCountry"))
// generates {$facet: {categorizedByYear: [
// { $project: { title: 1, publicationYear: { $year: "publicationDate"}}},
// { $bucketAuto: {groupBy: $price, buckets: 5, output: { titles: {$push:"$title"}}}
// ]}}
facet(project("title").and("publicationDate").extractYear().as("publicationYear"),
bucketAuto("publicationYear", 5).andOutput("title").push().as("titles"))
.as("categorizedByYear"))
请注意,有关分面操作的更多详细信息,可以在 $facet 章节 的 MongoDB 聚合框架参考文档中找到。
按数量排序
按计数排序操作会根据指定表达式的值对传入文档进行分组,计算每个不同分组中文档的数量,并按计数对结果进行排序。它在使用多面分类(Faceted Classification)时提供了一个便捷的排序快捷方式。按计数排序操作需要一个分组字段或分组表达式。以下示例展示了一个按计数排序的操作:
// generates { $sortByCount: "$country" }
sortByCount("country");
按计数排序的操作等同于以下 BSON(二进制 JSON):
{ $group: { _id: <expression>, count: { $sum: 1 } } },
{ $sort: { count: -1 } }
投影表达式中的 Spring 表达式支持
我们通过 andExpression 和 ProjectionOperation 类的 BucketOperation 方法,支持在投影表达式中使用 SpEL 表达式。此功能允许您将所需表达式定义为 SpEL 表达式。在执行查询时,SpEL 表达式会被转换为相应的 MongoDB 投影表达式部分。这种机制使得表达复杂计算变得更加容易。
使用 SpEL 表达式进行复杂计算
请考虑以下 SpEL 表达式:
1 + (q + 1) / (q - 1)
上述表达式被转换为以下投影表达式部分:
{ "$add" : [ 1, {
"$divide" : [ {
"$add":["$q", 1]}, {
"$subtract":[ "$q", 1]}
]
}]}
支持的 SpEL 转换
| SpEL 表达式 | Mongo 表达式部分 |
|---|---|
a == b |
{ $eq : [$a, $b] } |
a != b |
{ $ne : [$a , $b] } |
a > b |
{ $gt : [$a, $b] } |
a >= b |
{ $gte : [$a, $b] } |
a < b |
{ $lt : [$a, $b] } |
a ⇐ b |
{ $lte : [$a, $b] } |
a + b |
{ $add : [$a, $b] } |
a - b |
$subtract: [${a}, ${b}] |
a * b |
{ $multiply : [$a, $b] } |
a / b |
{ $divide : [$a, $b] } |
a^b |
{ $pow : [$a, $b] } |
a % b |
{ $mod : [$a, $b] } |
a && b |
{ $and : [$a, $b] } |
a || b |
{ $or : [$a, $b] } |
!a |
{ $not : [$a] } |
除了上表所示的转换之外,您还可以使用标准的 SpEL 操作(例如 new)来创建数组,并通过其名称引用表达式(后跟括号中的参数)。以下示例展示了如何以这种方式创建数组:
// { $setEquals : [$a, [5, 8, 13] ] }
.andExpression("setEquals(a, new int[]{5, 8, 13})");
聚合框架示例
本节中的示例演示了在 Spring Data MongoDB 中使用 MongoDB 聚合框架的模式。
聚合框架示例 1
在这个入门示例中,我们要对一个标签列表进行聚合,以获取 MongoDB 集合(名为 tags)中某个特定标签的出现次数,并按出现次数降序排序。该示例演示了分组、排序、投影(字段选择)和展开(结果拆分)的用法。
class TagCount {
String tag;
int n;
}
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
Aggregation agg = newAggregation(
project("tags"),
unwind("tags"),
group("tags").count().as("n"),
project("n").and("tag").previousOperation(),
sort(DESC, "n")
);
AggregationResults<TagCount> results = mongoTemplate.aggregate(agg, "tags", TagCount.class);
List<TagCount> tagCount = results.getMappedResults();
上述列表使用了以下算法:
-
通过使用
newAggregation静态工厂方法创建一个新的聚合操作,并向该方法传入一个聚合操作列表。这些聚合操作定义了我们Aggregation的聚合管道。 -
使用
project操作从输入集合中选择tags字段(该字段是一个字符串数组)。 -
使用
unwind操作为tags数组中的每个标签生成一个新文档。 -
使用
group操作为每个tags值定义一个分组,并通过count聚合操作符对出现次数进行聚合,将结果收集到一个名为n的新字段中。 -
选择
n字段,并为上一个分组操作生成的 ID 字段创建一个别名(因此调用previousOperation()),别名为tag。 -
使用
sort操作按标签出现次数的降序对生成的标签列表进行排序。 -
调用
aggregate上的MongoTemplate方法,并将创建好的Aggregation作为参数传入,以让 MongoDB 执行实际的聚合操作。
请注意,输入集合被显式指定为 tags 方法的 aggregate 参数。如果未显式指定输入集合的名称,则会根据传递给 newAggreation 方法的第一个参数的输入类来推导得出。
聚合框架示例 2
此示例基于 MongoDB 聚合框架文档中的按州划分的最大与最小城市示例。我们添加了额外的排序,以确保在不同版本的 MongoDB 中都能产生稳定的结果。在此示例中,我们希望使用聚合框架返回每个州人口最多和最少的城市。该示例展示了分组、排序和投影(字段选择)操作。
class ZipInfo {
String id;
String city;
String state;
@Field("pop") int population;
@Field("loc") double[] location;
}
class City {
String name;
int population;
}
class ZipInfoStats {
String id;
String state;
City biggestCity;
City smallestCity;
}
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
TypedAggregation<ZipInfo> aggregation = newAggregation(ZipInfo.class,
group("state", "city")
.sum("population").as("pop"),
sort(ASC, "pop", "state", "city"),
group("state")
.last("city").as("biggestCity")
.last("pop").as("biggestPop")
.first("city").as("smallestCity")
.first("pop").as("smallestPop"),
project()
.and("state").previousOperation()
.and("biggestCity")
.nested(bind("name", "biggestCity").and("population", "biggestPop"))
.and("smallestCity")
.nested(bind("name", "smallestCity").and("population", "smallestPop")),
sort(ASC, "state")
);
AggregationResults<ZipInfoStats> result = mongoTemplate.aggregate(aggregation, ZipInfoStats.class);
ZipInfoStats firstZipInfoStats = result.getMappedResults().get(0);
请注意,ZipInfo 类映射了给定输入集合的结构。ZipInfoStats 类定义了所需输出格式的结构。
前面的列表使用了以下算法:
-
使用
group操作从输入集合中定义一个分组。分组条件是state和city字段的组合,该组合构成了分组的 ID 结构。我们使用population运算符对分组元素中的sum属性值进行聚合,并将结果保存在pop字段中。 -
使用
sort操作按pop、state和city字段对中间结果进行升序排序,使得最小的城市排在结果顶部,最大的城市排在结果底部。请注意,对state和city的排序实际上是隐式地针对分组 ID 字段进行的(由 Spring Data MongoDB 处理)。 -
再次使用
group操作,按state对中间结果进行分组。注意,state再次隐式引用了一个组 ID 字段。在last(…)操作中,我们分别通过调用first(…)和project操作符,选取了最大城市和最小城市的名称及其人口数量。 -
从上一个
state操作中选择group字段。请注意,state再次隐式引用了一个组 ID 字段。由于我们不希望出现隐式生成的 ID,因此通过使用and(previousOperation()).exclude()将该 ID 从上一个操作中排除。又因为我们希望在输出类中填充嵌套的City结构,所以必须通过使用 nested 方法来生成相应的子文档。 -
在
StateStats操作中,将生成的sort列表按州名升序排序。
请注意,我们从作为 ZipInfo 方法第一个参数传入的 newAggregation 类中推导出输入集合的名称。
聚合框架示例 3
此示例基于 MongoDB 聚合框架文档中的人口超过一千万的州示例。我们添加了额外的排序,以确保在不同版本的 MongoDB 中都能产生稳定的结果。在此示例中,我们希望使用聚合框架返回所有人口超过一千万的州。该示例展示了分组(grouping)、排序(sorting)和匹配(过滤,matching)操作。
class StateStats {
@Id String id;
String state;
@Field("totalPop") int totalPopulation;
}
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
TypedAggregation<ZipInfo> agg = newAggregation(ZipInfo.class,
group("state").sum("population").as("totalPop"),
sort(ASC, previousOperation(), "totalPop"),
match(where("totalPop").gte(10 * 1000 * 1000))
);
AggregationResults<StateStats> result = mongoTemplate.aggregate(agg, StateStats.class);
List<StateStats> stateStatsList = result.getMappedResults();
前面的列表使用了以下算法:
-
根据
state字段对输入集合进行分组,并计算population字段的总和,将结果存储在新字段"totalPop"中。 -
除了按
"totalPop"字段升序排序外,还根据前一个分组操作的 id 引用对中间结果进行排序。 -
通过使用接受
match查询作为参数的Criteria操作来过滤中间结果。
请注意,我们从作为第一个参数传递给 ZipInfo 方法的 newAggregation 类派生出输入集合的名称。
聚合框架示例 4
此示例演示了在投影操作中使用简单算术运算。
class Product {
String id;
String name;
double netPrice;
int spaceUnits;
}
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
TypedAggregation<Product> agg = newAggregation(Product.class,
project("name", "netPrice")
.and("netPrice").plus(1).as("netPricePlus1")
.and("netPrice").minus(1).as("netPriceMinus1")
.and("netPrice").multiply(1.19).as("grossPrice")
.and("netPrice").divide(2).as("netPriceDiv2")
.and("spaceUnits").mod(2).as("spaceUnitsMod2")
);
AggregationResults<Document> result = mongoTemplate.aggregate(agg, Document.class);
List<Document> resultList = result.getMappedResults();
请注意,我们从作为第一个参数传递给 Product 方法的 newAggregation 类派生出输入集合的名称。
聚合框架示例 5
此示例演示了在投影操作中使用源自SpEL表达式的简单算术运算。
class Product {
String id;
String name;
double netPrice;
int spaceUnits;
}
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
TypedAggregation<Product> agg = newAggregation(Product.class,
project("name", "netPrice")
.andExpression("netPrice + 1").as("netPricePlus1")
.andExpression("netPrice - 1").as("netPriceMinus1")
.andExpression("netPrice / 2").as("netPriceDiv2")
.andExpression("netPrice * 1.19").as("grossPrice")
.andExpression("spaceUnits % 2").as("spaceUnitsMod2")
.andExpression("(netPrice * 0.8 + 1.2) * 1.19").as("grossPriceIncludingDiscountAndCharge")
);
AggregationResults<Document> result = mongoTemplate.aggregate(agg, Document.class);
List<Document> resultList = result.getMappedResults();
聚合框架示例 6
此示例演示了在投影操作中使用源自 SpEL 表达式的复杂算术运算。
注意:addExpression 方法传入的附加参数可以根据其位置通过索引表达式进行引用。在此示例中,我们使用 [0] 引用参数数组中的第一个参数。当 SpEL 表达式被转换为 MongoDB 聚合框架表达式时,外部参数表达式将被替换为其对应的值。
class Product {
String id;
String name;
double netPrice;
int spaceUnits;
}
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
double shippingCosts = 1.2;
TypedAggregation<Product> agg = newAggregation(Product.class,
project("name", "netPrice")
.andExpression("(netPrice * (1-discountRate) + [0]) * (1+taxRate)", shippingCosts).as("salesPrice")
);
AggregationResults<Document> result = mongoTemplate.aggregate(agg, Document.class);
List<Document> resultList = result.getMappedResults();
请注意,我们也可以在 SpEL 表达式中引用文档的其他字段。
聚合框架示例 7
此示例使用了条件投影。它源自$cond 参考文档。
public class InventoryItem {
@Id int id;
String item;
String description;
int qty;
}
public class InventoryItemProjection {
@Id int id;
String item;
String description;
int qty;
int discount
}
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
TypedAggregation<InventoryItem> agg = newAggregation(InventoryItem.class,
project("item").and("discount")
.applyCondition(ConditionalOperator.newBuilder().when(Criteria.where("qty").gte(250))
.then(30)
.otherwise(20))
.and(ifNull("description", "Unspecified")).as("description")
);
AggregationResults<InventoryItemProjection> result = mongoTemplate.aggregate(agg, "inventory", InventoryItemProjection.class);
List<InventoryItemProjection> stateStatsList = result.getMappedResults();
此单步聚合操作对 inventory 集合使用了投影操作。我们通过条件操作为所有数量(discount)大于或等于 qty 的库存项投影出 250 字段。此外,还对 description 字段执行了第二个条件投影操作:对于所有未包含 Unspecified 字段或 description 值为 null 的项目,统一应用 8 描述。
从 MongoDB 3.6 开始,可以使用条件表达式从投影中排除字段。
TypedAggregation<Book> agg = Aggregation.newAggregation(Book.class,
project("title")
.and(ConditionalOperators.when(ComparisonOperators.valueOf("author.middle") (1)
.equalToValue("")) (2)
.then("$$REMOVE") (3)
.otherwiseValueOf("author.middle") (4)
)
.as("author.middle"));
| 1 | 如果字段 author.middle 的值 |
| 2 | 不包含值, |
| 3 | 然后使用 $$REMOVE 来排除该字段。 |
| 4 | 否则,添加字段值 author.middle。 |