Skip to content

Commit 1fe79f1

Browse files
mp911dechristophstrobl
authored andcommitted
DATAMONGO-1585 - Expose synthetic fields in $project aggregation stage.
Field projections now expose their fields as synthetic simple fields. Projection aggregation stage redefines the available field set available for later aggregation stages entirely so projected fields are considered synthetic. A simple synthetic field has no target field which causes later aggregation stages to not pick up the underlying target but the exposed field name when rendering aggregation operations to Mongo documents. The change is motivated by a bug where previously an aggregation consisting of projection of an aliased field and sort caused the sort projection stage to render with the original field name instead of the aliased field. The sort did not apply any sorting since projection redefines the available field set entirely and the original field is no longer accessible. Original Pull Request: #433
1 parent 2c6bd6e commit 1fe79f1

File tree

4 files changed

+92
-17
lines changed

4 files changed

+92
-17
lines changed

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ProjectionOperation.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2013-2016 the original author or authors.
2+
* Copyright 2013-2017 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -28,6 +28,7 @@
2828
import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField;
2929
import org.springframework.data.mongodb.core.aggregation.Fields.AggregationField;
3030
import org.springframework.data.mongodb.core.aggregation.ProjectionOperation.ProjectionOperationBuilder.FieldProjection;
31+
import org.springframework.data.mongodb.core.aggregation.VariableOperators.Let.ExpressionVariable;
3132
import org.springframework.util.Assert;
3233

3334
/**
@@ -1206,8 +1207,9 @@ public ProjectionOperationBuilder dateAsFormattedString(String format) {
12061207
* @since 1.10
12071208
*/
12081209
public ProjectionOperationBuilder let(AggregationExpression valueExpression, String variableName,
1209-
AggregationExpression in) {
1210-
return this.operation.and(VariableOperators.Let.define(ExpressionVariable.newVariable(variableName).forExpression(valueExpression)).andApply(in));
1210+
AggregationExpression in) {
1211+
return this.operation.and(VariableOperators.Let
1212+
.define(ExpressionVariable.newVariable(variableName).forExpression(valueExpression)).andApply(in));
12111213
}
12121214

12131215
/**
@@ -1279,6 +1281,7 @@ public Document toDocument(AggregationOperationContext context) {
12791281
*
12801282
* @author Oliver Gierke
12811283
* @author Thomas Darimont
1284+
* @author Mark Paluch
12821285
*/
12831286
static class FieldProjection extends Projection {
12841287

@@ -1297,7 +1300,7 @@ public FieldProjection(String name, Object value) {
12971300

12981301
private FieldProjection(Field field, Object value) {
12991302

1300-
super(field);
1303+
super(new ExposedField(field.getName(), true));
13011304

13021305
this.field = field;
13031306
this.value = value;

spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/AggregationUnitTests.java

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2013-2016 the original author or authors.
2+
* Copyright 2013-2017 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -33,6 +33,7 @@
3333
import org.springframework.data.domain.Sort.Direction;
3434
import org.springframework.data.mongodb.core.aggregation.ConditionalOperators.Cond;
3535
import org.springframework.data.mongodb.core.query.Criteria;
36+
import org.springframework.data.mongodb.test.util.BasicDbListBuilder;
3637

3738
/**
3839
* Unit tests for {@link Aggregation}.
@@ -279,6 +280,47 @@ public void shouldSupportReferingToNestedPropertiesInGroupOperation() {
279280
assertThat(id.get("ruleType"), is((Object) "$rules.ruleType"));
280281
}
281282

283+
/**
284+
* @see DATAMONGO-1585
285+
*/
286+
@Test
287+
public void shouldSupportSortingBySyntheticAndExposedGroupFields() {
288+
289+
Document agg = newAggregation( //
290+
group("cmsParameterId").addToSet("title").as("titles"), //
291+
sort(Direction.ASC, "cmsParameterId", "titles") //
292+
).toDocument("foo", Aggregation.DEFAULT_CONTEXT);
293+
294+
assertThat(agg, is(notNullValue()));
295+
296+
Document sort = ((List<Document>) agg.get("pipeline")).get(1);
297+
298+
assertThat(getAsDocument(sort, "$sort"), is(Document.parse("{ \"_id.cmsParameterId\" : 1 , \"titles\" : 1}")));
299+
}
300+
301+
/**
302+
* @see DATAMONGO-1585
303+
*/
304+
@Test
305+
public void shouldSupportSortingByProjectedFields() {
306+
307+
Document agg = newAggregation( //
308+
project("cmsParameterId") //
309+
.and(SystemVariable.CURRENT + ".titles").as("titles") //
310+
.and("field").as("alias"), //
311+
sort(Direction.ASC, "cmsParameterId", "titles", "alias") //
312+
).toDocument("foo", Aggregation.DEFAULT_CONTEXT);
313+
314+
assertThat(agg, is(notNullValue()));
315+
316+
Document sort = ((List<Document>) agg.get("pipeline")).get(1);
317+
318+
assertThat(getAsDocument(sort, "$sort"),
319+
isBsonObject().containing("cmsParameterId", 1) //
320+
.containing("titles", 1) //
321+
.containing("alias", 1));
322+
}
323+
282324
/**
283325
* @see DATAMONGO-924
284326
*/
@@ -336,7 +378,7 @@ public void shouldRenderAggregationWithCustomOptionsCorrectly() {
336378
}
337379

338380
/**
339-
* @see DATAMONGO-954
381+
* @see DATAMONGO-954, DATAMONGO-1585
340382
*/
341383
@Test
342384
public void shouldSupportReferencingSystemVariables() {
@@ -345,15 +387,15 @@ public void shouldSupportReferencingSystemVariables() {
345387
project("someKey") //
346388
.and("a").as("a1") //
347389
.and(Aggregation.CURRENT + ".a").as("a2") //
348-
, sort(Direction.DESC, "a") //
390+
, sort(Direction.DESC, "a1") //
349391
, group("someKey").first(Aggregation.ROOT).as("doc") //
350392
).toDocument("foo", Aggregation.DEFAULT_CONTEXT);
351393

352394
Document projection0 = extractPipelineElement(agg, 0, "$project");
353395
assertThat(projection0, is((Document) new Document("someKey", 1).append("a1", "$a").append("a2", "$$CURRENT.a")));
354396

355397
Document sort = extractPipelineElement(agg, 1, "$sort");
356-
assertThat(sort, is((Document) new Document("a", -1)));
398+
assertThat(sort, is((Document) new Document("a1", -1)));
357399

358400
Document group = extractPipelineElement(agg, 2, "$group");
359401
assertThat(group, is((Document) new Document("_id", "$someKey").append("doc", new Document("$first", "$$ROOT"))));

spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/TypeBasedAggregationOperationContextUnitTests.java

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2013-2016 the original author or authors.
2+
* Copyright 2013-2017 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -103,7 +103,8 @@ public void returnsReferencesToNestedFieldsCorrectly() {
103103
public void aliasesIdFieldCorrectly() {
104104

105105
AggregationOperationContext context = getContext(Foo.class);
106-
assertThat(context.getReference("id"), is((FieldReference) new DirectFieldReference(new ExposedField(field("id", "_id"), true))));
106+
assertThat(context.getReference("id"),
107+
is((FieldReference) new DirectFieldReference(new ExposedField(field("id", "_id"), true))));
107108
}
108109

109110
/**
@@ -173,6 +174,23 @@ public void rendersAggregationOptionsInTypedAggregationContextCorrectly() {
173174
assertThat(document.get("cursor"), is((Object) new org.bson.Document("foo", 1)));
174175
}
175176

177+
/**
178+
* @see DATAMONGO-1585
179+
*/
180+
@Test
181+
public void rendersSortOfProjectedFieldCorrectly() {
182+
183+
TypeBasedAggregationOperationContext context = getContext(MeterData.class);
184+
TypedAggregation<MeterData> agg = newAggregation(MeterData.class, project().and("counterName").as("counter"), //
185+
sort(Direction.ASC, "counter"));
186+
187+
Document dbo = agg.toDocument("meterData", context);
188+
Document sort = getPipelineElementFromAggregationAt(dbo, 1);
189+
190+
Document definition = (Document) sort.get("$sort");
191+
assertThat(definition.get("counter"), is(equalTo((Object) 1)));
192+
}
193+
176194
/**
177195
* @see DATAMONGO-1133
178196
*/
@@ -192,21 +210,23 @@ public void shouldHonorAliasedFieldsInGroupExpressions() {
192210
}
193211

194212
/**
195-
* @see DATAMONGO-1326
213+
* @see DATAMONGO-1326, DATAMONGO-1585
196214
*/
197215
@Test
198216
public void lookupShouldInheritFieldsFromInheritingAggregationOperation() {
199217

200218
TypeBasedAggregationOperationContext context = getContext(MeterData.class);
201219
TypedAggregation<MeterData> agg = newAggregation(MeterData.class,
202-
lookup("OtherCollection", "resourceId", "otherId", "lookup"), sort(Direction.ASC, "resourceId"));
220+
lookup("OtherCollection", "resourceId", "otherId", "lookup"), //
221+
sort(Direction.ASC, "resourceId", "counterName"));
203222

204223
org.bson.Document document = agg.toDocument("meterData", context);
205224
org.bson.Document sort = getPipelineElementFromAggregationAt(document, 1);
206225

207226
org.bson.Document definition = (org.bson.Document) sort.get("$sort");
208227

209228
assertThat(definition.get("resourceId"), is(equalTo((Object) 1)));
229+
assertThat(definition.get("counter_name"), is(equalTo((Object) 1)));
210230
}
211231

212232
/**

src/main/asciidoc/reference/mongodb.adoc

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1734,8 +1734,8 @@ Note that the aggregation operations not listed here are currently not supported
17341734
[[mongo.aggregation.projection]]
17351735
=== Projection Expressions
17361736

1737-
Projection expressions are used to define the fields that are the outcome of a particular aggregation step. Projection expressions can be defined via the `project` method of the `Aggregate` class either by passing a list of `String` 's or an aggregation framework `Fields` object. The projection can be extended with additional fields through a fluent API via the `and(String)` method and aliased via the `as(String)` method.
1738-
Note that one can also define fields with aliases via the static factory method `Fields.field` of the aggregation framework that can then be used to construct a new `Fields` instance.
1737+
Projection expressions are used to define the fields that are the outcome of a particular aggregation step. Projection expressions can be defined via the `project` method of the `Aggregate` class either by passing a list of ``String``'s or an aggregation framework `Fields` object. The projection can be extended with additional fields through a fluent API via the `and(String)` method and aliased via the `as(String)` method.
1738+
Note that one can also define fields with aliases via the static factory method `Fields.field` of the aggregation framework that can then be used to construct a new `Fields` instance. References to projected fields in later aggregation stages are only valid by using the field name of included fields or their alias of aliased or newly defined fields. Fields not included in the projection cannot be referenced in later aggregation stages.
17391739

17401740
.Projection expression examples
17411741
====
@@ -1747,9 +1747,19 @@ project("a","b").and("foo").as("bar") // will generate {$project: {a: 1, b: 1, b
17471747
----
17481748
====
17491749

1750-
Note that more examples for project operations can be found in the `AggregationTests` class.
1750+
.Multi-Stage Aggregation using Projection and Sorting
1751+
====
1752+
[source,java]
1753+
----
1754+
project("name", "netPrice"), sort(ASC, "name") // will generate {$project: {name: 1, netPrice: 1}}, {$sort: {name: 1}}
1755+
1756+
project().and("foo").as("bar"), sort(ASC, "bar") // will generate {$project: {bar: $foo}}, {$sort: {bar: 1}}
1757+
1758+
project().and("foo").as("bar"), sort(ASC, "foo") // this will not work
1759+
----
1760+
====
17511761

1752-
Note that further details regarding the projection expressions can be found in the http://docs.mongodb.org/manual/reference/operator/aggregation/project/#pipe._S_project[corresponding section] of the MongoDB Aggregation Framework reference documentation.
1762+
More examples for project operations can be found in the `AggregationTests` class. Note that further details regarding the projection expressions can be found in the http://docs.mongodb.org/manual/reference/operator/aggregation/project/#pipe._S_project[corresponding section] of the MongoDB Aggregation Framework reference documentation.
17531763

17541764
[[mongo.aggregation.projection.expressions]]
17551765
==== Spring Expression Support in Projection Expressions
@@ -1922,7 +1932,7 @@ ZipInfoStats firstZipInfoStats = result.getMappedResults().get(0);
19221932

19231933
* The class `ZipInfo` maps the structure of the given input-collection. The class `ZipInfoStats` defines the structure in the desired output format.
19241934
* As a first step we use the `group` operation to define a group from the input-collection. The grouping criteria is the combination of the fields `"state"` and `"city"` which forms the id structure of the group. We aggregate the value of the `"population"` property from the grouped elements with by using the `sum` operator saving the result in the field `"pop"`.
1925-
* In a second step we use the `sort` operation to sort the intermediate-result by the fields `"pop"`, `"state"` and `"city"` in ascending order, such that the smallest city is at the top and the biggest city is at the bottom of the result. Note that the sorting on "state" and `"city"` is implicitly performed against the group id fields which Spring Data MongoDB took care of.
1935+
* In a second step we use the `sort` operation to sort the intermediate-result by the fields `"pop"`, `"state"` and `"city"` in ascending order, such that the smallest city is at the top and the biggest city is at the bottom of the result. Note that the sorting on `"state"` and `"city"` is implicitly performed against the group id fields which Spring Data MongoDB took care of.
19261936
* In the third step we use a `group` operation again to group the intermediate result by `"state"`. Note that `"state"` again implicitly references an group-id field. We select the name and the population count of the biggest and smallest city with calls to the `last(…)` and `first(...)` operator respectively via the `project` operation.
19271937
* As the forth step we select the `"state"` field from the previous `group` operation. Note that `"state"` again implicitly references an group-id field. As we do not want an implicitly generated id to appear, we exclude the id from the previous operation via `and(previousOperation()).exclude()`. As we want to populate the nested `City` structures in our output-class accordingly we have to emit appropriate sub-documents with the nested method.
19281938
* Finally as the fifth step we sort the resulting list of `StateStats` by their state name in ascending order via the `sort` operation.

0 commit comments

Comments
 (0)