Skip to content

Commit

Permalink
Fix expression evaluation for documents in a List for projections.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaizer Poonawala committed Dec 21, 2020
1 parent 2d81ecc commit a6c79a4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
Expand Up @@ -2,7 +2,9 @@

import static de.bwaldvogel.mongo.backend.Constants.ID_FIELD;

import java.util.List;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import de.bwaldvogel.mongo.backend.Missing;
Expand Down Expand Up @@ -54,7 +56,15 @@ Document projectDocument(Document document) {
} else {
Utils.removeSubdocumentValue(result, field);
}
} else if (projectionValue == null) {
}
else if (projectionValue instanceof List) {
List<Object> resolvedProjectionValues = ((List<Object>) projectionValue)
.stream()
.map(value -> Expression.evaluateDocument(value, document))
.collect(Collectors.toList());
result.put(field, resolvedProjectionValues);
}
else if (projectionValue == null) {
result.put(field, null);
} else {
Object value = Expression.evaluateDocument(projectionValue, document);
Expand Down
Expand Up @@ -4,6 +4,8 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import java.util.Collections;

import org.junit.jupiter.api.Test;

import de.bwaldvogel.mongo.bson.Document;
Expand Down Expand Up @@ -41,6 +43,24 @@ void testProject_withNestedInclusion() throws Exception {
.isEqualTo(json("_id: 1, x: {b: 2, c: 3}"));
}

@Test
void testProject_withFieldToBeEvaluated() {
Document projection = new Document();
projection.put("_id", 1);
projection.put("x", new Document("count", "$count"));
assertThat(project(json("_id: 1, count: 5"), projection))
.isEqualTo(json("_id: 1, x: {count: 5}"));
}

@Test
void testProject_withFieldWithinArrayToBeEvaluated() {
Document projection = new Document();
projection.put("_id", 1);
projection.put("x", Collections.singletonList(new Document("count", "$count")));
assertThat(project(json("_id: 1, count: 5"), projection))
.isEqualTo(json("_id: 1, x: [{count: 5}]"));
}

private static Document project(Document document, Document projection) {
return new ProjectStage(projection).projectDocument(document);
}
Expand Down

0 comments on commit a6c79a4

Please sign in to comment.