Skip to content

Commit f5a04fb

Browse files
Thomas Darimontodrotbohm
Thomas Darimont
authored andcommitted
DATAMONGO-908 - Support for nested field references in group operations.
We now allow referring to nested field expressions if the root segment of the nested field expression was exposed in earlier stages of the aggregation pipeline. Original pull request: spring-projects#167.
1 parent 88558b6 commit f5a04fb

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

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

+15-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2013 the original author or authors.
2+
* Copyright 2013-2014 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.
@@ -69,12 +69,26 @@ public FieldReference getReference(Field field) {
6969
@Override
7070
public FieldReference getReference(String name) {
7171

72+
Assert.notNull(name, "Name must not be null!");
73+
7274
ExposedField field = exposedFields.getField(name);
7375

7476
if (field != null) {
7577
return new FieldReference(field);
7678
}
7779

80+
if (name.contains(".")) {
81+
82+
// for nested field references we only check that the root field exists.
83+
ExposedField rootField = exposedFields.getField(name.split("\\.")[0]);
84+
85+
if (rootField != null) {
86+
87+
// We have to synthetic to true, in order to render the field-name as is.
88+
return new FieldReference(new ExposedField(name, true));
89+
}
90+
}
91+
7892
throw new IllegalArgumentException(String.format("Invalid reference '%s'!", name));
7993
}
8094
}

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

+21
Original file line numberDiff line numberDiff line change
@@ -179,4 +179,25 @@ public void expressionBasedFieldsShouldBeReferencableInFollowingOperations() {
179179
DBObject fields = getAsDBObject(secondProjection, "$group");
180180
assertThat(fields.get("foosum"), is((Object) new BasicDBObject("$sum", "$foo")));
181181
}
182+
183+
/**
184+
* @see DATAMONGO-908
185+
*/
186+
@Test
187+
public void shouldSupportReferingToNestedPropertiesInGroupOperation() {
188+
189+
DBObject agg = newAggregation( //
190+
project("cmsParameterId", "rules"), //
191+
unwind("rules"), //
192+
group("cmsParameterId", "rules.ruleType").count().as("totol") //
193+
).toDbObject("foo", Aggregation.DEFAULT_CONTEXT);
194+
195+
assertThat(agg, is(notNullValue()));
196+
197+
DBObject group = ((List<DBObject>) agg.get("pipeline")).get(2);
198+
DBObject fields = getAsDBObject(group, "$group");
199+
DBObject id = getAsDBObject(fields, "_id");
200+
201+
assertThat(id.get("ruleType"), is((Object) "$rules.ruleType"));
202+
}
182203
}

0 commit comments

Comments
 (0)