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.

Resolves: #4933
Original Pull Request: #4959

Signed-off-by: kssumin <201566@jnu.ac.kr>
This commit is contained in:
kssumin
2025-05-02 10:02:31 +09:00
committed by Christoph Strobl
parent bb13d9b9aa
commit ddf61dceb0
2 changed files with 19 additions and 1 deletions

View File

@@ -31,6 +31,7 @@ import org.springframework.lang.Nullable;
* </pre>
*
* @author Christoph Strobl
* @author Kim Sumin
* @since 3.0
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/">MongoDB Aggregation
* Framework: $addFields</a>
@@ -148,7 +149,7 @@ public class AddFieldsOperation extends DocumentEnhancingOperation {
@Override
public AddFieldsOperationBuilder withValueOf(Object value) {
valueMap.put(field, value instanceof String stringValue ? Fields.fields(stringValue) : value);
valueMap.put(field, value instanceof String stringValue ? Fields.field(stringValue) : value);
return AddFieldsOperationBuilder.this;
}

View File

@@ -33,6 +33,7 @@ import org.springframework.lang.Nullable;
*
* @author Christoph Strobl
* @author Mark Paluch
* @author Kim Sumin
*/
class AddFieldsOperationUnitTests {
@@ -127,6 +128,22 @@ class AddFieldsOperationUnitTests {
assertThat(fields.getField("does-not-exist")).isNull();
}
@Test // DATAMONGO-4933
void rendersStringValueAsFieldReferenceCorrectly() {
AddFieldsOperation operation = AddFieldsOperation.builder().addField("name").withValueOf("value").build();
assertThat(operation.toPipelineStages(contextFor(Scores.class)))
.containsExactly(Document.parse("{\"$addFields\" : {\"name\":\"$value\"}}"));
AddFieldsOperation mappedOperation = AddFieldsOperation.builder().addField("totalHomework").withValueOf("homework")
.build();
assertThat(mappedOperation.toPipelineStages(contextFor(ScoresWithMappedField.class)))
.containsExactly(Document.parse("{\"$addFields\" : {\"totalHomework\":\"$home_work\"}}"));
}
private static AggregationOperationContext contextFor(@Nullable Class<?> type) {
if (type == null) {