Skip to content

Commit 5842973

Browse files
author
kssumin
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#4957 Signed-off-by: kssumin <205166@jnu.ac.kr>
1 parent 9496d1b commit 5842973

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-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

+16
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,22 @@ void exposesFieldsCorrectly() {
127127
assertThat(fields.getField("does-not-exist")).isNull();
128128
}
129129

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

132148
if (type == null) {

0 commit comments

Comments
 (0)