Skip to content

Commit c607c8a

Browse files
committed
Fix AddFieldsOperationBuilder to treat String value as Field reference
This commit modifies the AddFieldsOperationBuilder to correctly treat String values as field references. When a String value is passed, it is now interpreted as a reference to another field, following MongoDB's field reference syntax. Closes spring-projects#4933 Signed-off-by: kssumin <201566@jnu.ac.kr>
1 parent 9496d1b commit c607c8a

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

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

+2-1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
* </pre>
3232
*
3333
* @author Christoph Strobl
34+
* @author Kim Sumin
3435
* @since 3.0
3536
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/">MongoDB Aggregation
3637
* Framework: $addFields</a>
@@ -148,7 +149,7 @@ public AddFieldsOperationBuilder withValue(Object value) {
148149
@Override
149150
public AddFieldsOperationBuilder withValueOf(Object value) {
150151

151-
valueMap.put(field, value instanceof String stringValue ? Fields.fields(stringValue) : value);
152+
valueMap.put(field, value instanceof String stringValue ? Fields.field(stringValue) : value);
152153
return AddFieldsOperationBuilder.this;
153154
}
154155

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

+17
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
*
3434
* @author Christoph Strobl
3535
* @author Mark Paluch
36+
* @author Kim Sumin
3637
*/
3738
class AddFieldsOperationUnitTests {
3839

@@ -127,6 +128,22 @@ void exposesFieldsCorrectly() {
127128
assertThat(fields.getField("does-not-exist")).isNull();
128129
}
129130

131+
@Test // DATAMONGO-4933
132+
void rendersStringValueAsFieldReferenceCorrectly() {
133+
134+
AddFieldsOperation operation = AddFieldsOperation.builder().addField("name").withValueOf("value").build();
135+
136+
assertThat(operation.toPipelineStages(contextFor(Scores.class)))
137+
.containsExactly(Document.parse("{\"$addFields\" : {\"name\":\"$value\"}}"));
138+
139+
AddFieldsOperation mappedOperation = AddFieldsOperation.builder().addField("totalHomework").withValueOf("homework")
140+
.build();
141+
142+
assertThat(mappedOperation.toPipelineStages(contextFor(ScoresWithMappedField.class)))
143+
.containsExactly(Document.parse("{\"$addFields\" : {\"totalHomework\":\"$home_work\"}}"));
144+
}
145+
146+
130147
private static AggregationOperationContext contextFor(@Nullable Class<?> type) {
131148

132149
if (type == null) {

0 commit comments

Comments
 (0)