From c1e285a87ca150aeba81dccb8ffc383b56e8d865 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Mon, 16 Nov 2026 12:17:02 +0100 Subject: [PATCH 1/2] Simplify aggregation stage tests --- .../stage/AbstractLookupStageTest.java | 2 +- .../aggregation/stage/AddFieldsStageTest.java | 2 +- .../stage/GraphLookupStageTest.java | 9 +- .../aggregation/stage/LookupStageTest.java | 107 +++++++++++++++--- .../stage/LookupWithPipelineStageTest.java | 9 +- .../stage/ReplaceRootStageTest.java | 2 +- .../aggregation/stage/UnwindStageTest.java | 2 +- .../backend/AbstractAggregationTest.java | 73 +++++++++--- 8 files changed, 168 insertions(+), 38 deletions(-) diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/AbstractLookupStageTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/AbstractLookupStageTest.java index 27bfb4dd5..dd9e759ec 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/AbstractLookupStageTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/AbstractLookupStageTest.java @@ -7,7 +7,7 @@ import de.bwaldvogel.mongo.MongoDatabase; @ExtendWith(MockitoExtension.class) -public abstract class AbstractLookupStageTest { +abstract class AbstractLookupStageTest { @Mock MongoDatabase database; diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/AddFieldsStageTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/AddFieldsStageTest.java index cce9b76b3..cabc48d29 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/AddFieldsStageTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/AddFieldsStageTest.java @@ -9,7 +9,7 @@ import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerError; -public class AddFieldsStageTest { +class AddFieldsStageTest { @Test void testAddFields() { diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStageTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStageTest.java index c13efe99b..c4af163c2 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStageTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStageTest.java @@ -29,7 +29,14 @@ void setUp() { @Test void testGraphLookupObjectThatHasLinkedDocuments() { - GraphLookupStage graphLookupStage = buildGraphLookupStage("from: 'employees', 'startWith': '$manager', 'connectFromField': 'manager', 'connectToField': 'name', 'as': 'managers', 'depthField': 'order'"); + GraphLookupStage graphLookupStage = buildGraphLookupStage(""" + from: 'employees', + 'startWith': '$manager', + 'connectFromField': 'manager', + 'connectToField': 'name', + 'as': 'managers', + 'depthField': 'order' + """); configureEmployeesCollection("name: 'Dave'", "_id: 2, name: 'Dave', manager: 'Mike'"); configureEmployeesCollection("name: 'Mike'", "_id: 1, name: 'Mike'"); Document document = json("name: 'Bob', manager: 'Dave'"); diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStageTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStageTest.java index 64dead435..a95a8a9ce 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStageTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStageTest.java @@ -15,14 +15,18 @@ import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerException; -public class LookupStageTest extends AbstractLookupStageTest { +class LookupStageTest extends AbstractLookupStageTest { @Mock private MongoCollection authorsCollection; @Test void testMissingFromField() { - assertThatThrownBy(() -> buildLookupStage("localField: 'authorId', foreignField: '_id', as: 'author'")) + assertThatThrownBy(() -> buildLookupStage(""" + localField: 'authorId', + foreignField: '_id', + as: 'author' + """)) .isInstanceOf(MongoServerException.class) .hasMessage("[Error 9] missing 'from' option to $lookup stage specification: " + "{\"localField\" : \"authorId\", \"foreignField\" : \"_id\", \"as\" : \"author\"}"); @@ -30,7 +34,11 @@ void testMissingFromField() { @Test void testMissingLocalFieldField() { - assertThatThrownBy(() -> buildLookupStage("from: 'authors', foreignField: '_id', as: 'author'")) + assertThatThrownBy(() -> buildLookupStage(""" + from: 'authors', + foreignField: '_id', + as: 'author' + """)) .isInstanceOf(MongoServerException.class) .hasMessage("[Error 9] missing 'localField' option to $lookup stage specification: " + "{\"from\" : \"authors\", \"foreignField\" : \"_id\", \"as\" : \"author\"}"); @@ -38,7 +46,11 @@ void testMissingLocalFieldField() { @Test void testMissingForeignFieldField() { - assertThatThrownBy(() -> buildLookupStage("from: 'authors', localField: 'authorId', as: 'author'")) + assertThatThrownBy(() -> buildLookupStage(""" + from: 'authors', + localField: 'authorId', + as: 'author' + """)) .isInstanceOf(MongoServerException.class) .hasMessage("[Error 9] missing 'foreignField' option to $lookup stage specification: " + "{\"from\" : \"authors\", \"localField\" : \"authorId\", \"as\" : \"author\"}"); @@ -46,7 +58,11 @@ void testMissingForeignFieldField() { @Test void testMissingAsField() { - assertThatThrownBy(() -> buildLookupStage("from: 'authors', localField: 'authorId', foreignField: '_id'")) + assertThatThrownBy(() -> buildLookupStage(""" + from: 'authors', + localField: 'authorId', + foreignField: '_id' + """)) .isInstanceOf(MongoServerException.class) .hasMessage("[Error 9] missing 'as' option to $lookup stage specification: " + "{\"from\" : \"authors\", \"localField\" : \"authorId\", \"foreignField\" : \"_id\"}"); @@ -54,14 +70,25 @@ void testMissingAsField() { @Test void testFromFieldWithWrongType() { - assertThatThrownBy(() -> buildLookupStage("from: 1, localField: 'authorId', foreignField: '_id', as: 'author'")) + assertThatThrownBy(() -> buildLookupStage(""" + from: 1, + localField: 'authorId', + foreignField: '_id', + as: 'author' + """)) .isInstanceOf(MongoServerException.class) .hasMessage("[Error 9] 'from' option to $lookup must be a string, but was type int"); } @Test void testUnexpectedConfigurationField() { - assertThatThrownBy(() -> buildLookupStage("from: 'authors', localField: 'authorId', foreignField: '_id', as: 'author', unknown: 'hello'")) + assertThatThrownBy(() -> buildLookupStage(""" + from: 'authors', + localField: 'authorId', + foreignField: '_id', + as: 'author', + unknown: 'hello' + """)) .isInstanceOf(MongoServerException.class) .hasMessage("[Error 9] unknown argument to $lookup: unknown"); } @@ -70,7 +97,12 @@ void testUnexpectedConfigurationField() { void testLookupObjectThatExists() { prepareAuthorsCollectionMock(); - LookupStage lookupStage = buildLookupStage("from: 'authors', 'localField': 'authorId', foreignField: '_id', as: 'author'"); + LookupStage lookupStage = buildLookupStage(""" + from: 'authors', + 'localField': 'authorId', + foreignField: '_id', + as: 'author' + """); configureAuthorsCollection("_id: 3", "_id: 3, name: 'Uncle Bob'"); Document document = json("title: 'Clean Code', authorId: 3"); @@ -85,7 +117,12 @@ void testLookupObjectThatExists() { void testLookupObjectThatExistsMultipleTimes() { prepareAuthorsCollectionMock(); - LookupStage lookupStage = buildLookupStage("from: 'authors', 'localField': 'job', foreignField: 'job', as: 'seeAuthors'"); + LookupStage lookupStage = buildLookupStage(""" + from: 'authors', + 'localField': 'job', + foreignField: 'job', + as: 'seeAuthors' + """); configureAuthorsCollection("job: 'Developer'", "_id: 3, name: 'Uncle Bob', job: 'Developer'", "_id: 5, name: 'Alice', job: 'Developer'"); @@ -94,8 +131,15 @@ void testLookupObjectThatExistsMultipleTimes() { Stream result = lookupStage.apply(Stream.of(document)); assertThat(result).containsExactly( - json("_id: 1, title: 'Developing for dummies', job: 'Developer', " + - "seeAuthors: [{_id: 3, name: 'Uncle Bob', job: 'Developer'}, {_id: 5, name: 'Alice', job: 'Developer'}]") + json(""" + _id: 1, + title: 'Developing for dummies', + job: 'Developer', + seeAuthors: [ + {_id: 3, name: 'Uncle Bob', job: 'Developer'}, + {_id: 5, name: 'Alice', job: 'Developer'} + ] + """) ); } @@ -103,7 +147,12 @@ void testLookupObjectThatExistsMultipleTimes() { void testLookupObjectThatDoesNotExist() { prepareAuthorsCollectionMock(); - LookupStage lookupStage = buildLookupStage("from: 'authors', 'localField': 'job', foreignField: 'job', as: 'seeAuthors'"); + LookupStage lookupStage = buildLookupStage(""" + from: 'authors', + 'localField': 'job', + foreignField: 'job', + as: 'seeAuthors' + """); configureAuthorsCollection("job: 'Developer'"); Document document = json("_id: 1, title: 'Developing for dummies', job: 'Developer'"); @@ -118,7 +167,12 @@ void testLookupObjectThatDoesNotExist() { void testLookupObjectBasedOnAnArrayKey() { prepareAuthorsCollectionMock(); - LookupStage lookupStage = buildLookupStage("from: 'authors', 'localField': 'authorsIds', foreignField: '_id', as: 'authors'"); + LookupStage lookupStage = buildLookupStage(""" + from: 'authors', + 'localField': 'authorsIds', + foreignField: '_id', + as: 'authors' + """); configureAuthorsCollection("_id: {$in: [3, 20, 22]}", "_id: 3, name: 'Uncle Bob'", "_id: 20, name: 'Martin Fowler'"); configureAuthorsCollection("_id: {$in: [3]}", "_id: 3, name: 'Uncle Bob'"); @@ -128,16 +182,28 @@ void testLookupObjectBasedOnAnArrayKey() { Stream result = lookupStage.apply(Stream.of(document1, document2)); assertThat(result).containsExactly( - json("title: 'Agile Manifesto', authorsIds: [3, 20, 22], authors: [{_id: 3, name: 'Uncle Bob'}, {_id: 20, name: 'Martin Fowler'}]"), + json(""" + title: 'Agile Manifesto', + authorsIds: [3, 20, 22], + authors: [ + {_id: 3, name: 'Uncle Bob'}, + {_id: 20, name: 'Martin Fowler'} + ] + """), json("title: 'Clean Code', authorsIds: [3], authors: [{_id: 3, name: 'Uncle Bob'}]") ); } @Test - public void testLookupWithNestedField() { + void testLookupWithNestedField() { prepareAuthorsCollectionMock(); - LookupStage lookupStage = buildLookupStage("from: 'authors', 'localField': 'author.id', foreignField: '_id', as: 'author'"); + LookupStage lookupStage = buildLookupStage(""" + from: 'authors', + 'localField': 'author.id', + foreignField: '_id', + as: 'author' + """); configureAuthorsCollection("_id: 3", "_id: 3, name: 'Uncle Bob'"); Document document = json("title: 'Clean Code', author: { id: 3 }"); @@ -149,10 +215,15 @@ public void testLookupWithNestedField() { } @Test - public void testLookupWithNestedFieldArray() { + void testLookupWithNestedFieldArray() { prepareAuthorsCollectionMock(); - LookupStage lookupStage = buildLookupStage("from: 'authors', 'localField': 'author.id', foreignField: '_id', as: 'author'"); + LookupStage lookupStage = buildLookupStage(""" + from: 'authors', + 'localField': 'author.id', + foreignField: '_id', + as: 'author' + """); configureAuthorsCollection("_id: {$in: [3, 4]}", "_id: 3, name: 'Uncle Bob'", "_id: 4, name: 'Aunt Bobby'"); Document document = json("title: 'Clean Code', author: [{ id: 3 }, {id: 4}]"); diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupWithPipelineStageTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupWithPipelineStageTest.java index cb400f9f9..2082be697 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupWithPipelineStageTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupWithPipelineStageTest.java @@ -9,11 +9,16 @@ import de.bwaldvogel.mongo.exception.MongoServerException; import de.bwaldvogel.mongo.oplog.NoopOplog; -public class LookupWithPipelineStageTest extends AbstractLookupStageTest { +class LookupWithPipelineStageTest extends AbstractLookupStageTest { @Test void testUnexpectedConfigurationField() { - assertThatThrownBy(() -> buildLookupStage("from: 'authors', pipeline: [], as: 'author', unknown: 'hello'")) + assertThatThrownBy(() -> buildLookupStage(""" + from: 'authors', + pipeline: [], + as: 'author', + unknown: 'hello' + """)) .isInstanceOf(MongoServerException.class) .hasMessage("[Error 9] unknown argument to $lookup: unknown"); } diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStageTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStageTest.java index 2a12110c0..89fab337f 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStageTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStageTest.java @@ -9,7 +9,7 @@ import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerError; -public class ReplaceRootStageTest { +class ReplaceRootStageTest { @Test void testReplaceRoot() { diff --git a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/UnwindStageTest.java b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/UnwindStageTest.java index f1d2f8b1f..216490f69 100644 --- a/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/UnwindStageTest.java +++ b/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/UnwindStageTest.java @@ -13,7 +13,7 @@ import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerError; -public class UnwindStageTest { +class UnwindStageTest { @Test void testUnwind() { diff --git a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java index 5c9640e2a..129e97745 100644 --- a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java +++ b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java @@ -1380,7 +1380,14 @@ void testAggregateWithLookup() { authorsCollection.insertOne(json("_id: 2, name: 'Martin Fowler'")); authorsCollection.insertOne(json("_id: null, name: 'Null Author'")); - List pipeline = jsonList("$lookup: {from: 'authors', localField: 'authorId', foreignField: '_id', as: 'author'}"); + List pipeline = jsonList(""" + $lookup: { + from: 'authors', + localField: 'authorId', + foreignField: '_id', + as: 'author' + } + """); assertThat(collection.aggregate(pipeline)).isEmpty(); @@ -1433,8 +1440,14 @@ void testAggregateWithLookupLocalArrayValues(String localField, String input, Li authorsCollection.insertMany(jsonList("_id: 1, key: 3", "_id: 2, key: null", "_id: 3")); collection.insertOne(json(input).append("_id", 1)); - List pipeline = jsonList("$lookup: {from: 'authors', localField: '" + localField + - "', foreignField: 'key', as: 'matches'}"); + List pipeline = jsonList(""" + $lookup: { + from: 'authors', + localField: '%s', + foreignField: 'key', + as: 'matches' + } + """.formatted(localField)); assertThat(collection.aggregate(pipeline)) .containsExactly(json(input).append("_id", 1).append("matches", expectedMatches)); @@ -1446,8 +1459,14 @@ void testAggregateWithLookupMatchingMultipleLocalValues() { authorsCollection.insertOne(json("_id: 1, keys: [3, 4]")); collection.insertOne(json("_id: 1, author: [{id: 3}, {id: 4}]")); - List pipeline = jsonList( - "$lookup: {from: 'authors', localField: 'author.id', foreignField: 'keys', as: 'matches'}"); + List pipeline = jsonList(""" + $lookup: { + from: 'authors', + localField: 'author.id', + foreignField: 'keys', + as: 'matches' + } + """); assertThat(collection.aggregate(pipeline)) .containsExactly(json("_id: 1, author: [{id: 3}, {id: 4}], matches: [{_id: 1, keys: [3, 4]}]")); @@ -1462,8 +1481,14 @@ void testAggregateWithLookupNestedForeignArrayField() { )); collection.insertOne(json("_id: 1, someKey: 'b'")); - List pipeline = jsonList("$lookup: {from: 'authors', localField: 'someKey'," + - " foreignField: 'nestedKeyCollection.nestedKey', as: 'matches'}"); + List pipeline = jsonList(""" + $lookup: { + from: 'authors', + localField: 'someKey', + foreignField: 'nestedKeyCollection.nestedKey', + as: 'matches' + } + """); assertThat(collection.aggregate(pipeline)) .containsExactly(json(""" @@ -1475,7 +1500,14 @@ void testAggregateWithLookupNestedForeignArrayField() { // https://github.com/bwaldvogel/mongo-java-server/issues/123 @Test void testAggregateWithLookup_collectionDoesNotExist() { - List pipeline = jsonList("$lookup: {from: 'authors', localField: 'authorId', foreignField: '_id', as: 'author'}"); + List pipeline = jsonList(""" + $lookup: { + from: 'authors', + localField: 'authorId', + foreignField: '_id', + as: 'author' + } + """); assertThat(collection.aggregate(pipeline)).isEmpty(); @@ -1509,9 +1541,13 @@ void testAggregateWithLookupAndPipeline() { MongoCollection ordersCollection = db.getCollection("orders"); MongoCollection itemsCollection = db.getCollection("items"); - List pipeline = jsonList("$lookup: {from: 'items'," + - " pipeline: [{$project: {item: 1, _id: 0}}]," + - " as: 'items'}"); + List pipeline = jsonList(""" + $lookup: { + from: 'items', + pipeline: [{$project: {item: 1, _id: 0}}], + as: 'items' + } + """); assertThat(ordersCollection.aggregate(pipeline)).isEmpty(); @@ -1659,8 +1695,19 @@ void testAggregateWithMergeObjects() { items.insertOne(json("_id: 3, item: 'jkl', description: 'product 3', instock: 60")); List pipeline = jsonList( - "$lookup: {from: 'items', localField: 'item', foreignField: 'item', as: 'fromItems'}", - "$replaceRoot: {newRoot: {$mergeObjects: [{$arrayElemAt: ['$fromItems', 0 ]}, '$$ROOT']}}", + """ + $lookup: { + from: 'items', + localField: 'item', + foreignField: 'item', + as: 'fromItems' + } + """, + """ + $replaceRoot: { + newRoot: {$mergeObjects: [{$arrayElemAt: ['$fromItems', 0 ]}, '$$ROOT']} + } + """, "$project: { fromItems: 0 }" ); From 2a4271cafa3ac8bf4c576c1a0f3c735eaf6a0bed Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Mon, 16 Nov 2026 12:17:02 +0100 Subject: [PATCH 2/2] Prevent aggregations from modifying stored documents --- .../backend/aggregation/Aggregation.java | 10 +- .../aggregation/stage/GraphLookupStage.java | 2 +- .../aggregation/stage/LookupStage.java | 4 +- .../backend/AbstractAggregationTest.java | 149 ++++++++++++++++++ 4 files changed, 158 insertions(+), 7 deletions(-) diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java index d91009a34..6be591630 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java @@ -56,7 +56,7 @@ public class Aggregation { private final MongoCollection collection; private final List stages = new ArrayList<>(); - private Map variables = Collections.emptyMap(); + private Document variables = new Document(); private Aggregation(MongoCollection collection) { this.collection = collection; @@ -198,6 +198,7 @@ public List runStages(Stream stream) { } public Stream runStagesAsStream(Stream stream) { + stream = stream.map(Document::cloneDeeply); if (hasVariables()) { stream = stream.map(this::addAllVariables); } @@ -215,9 +216,8 @@ private boolean hasVariables() { } private Document addAllVariables(Document document) { - Document clone = document.clone(); - clone.putAll(variables); - return clone; + variables.cloneInto(document); + return document; } private Document removeAllVariables(Document document) { @@ -245,7 +245,7 @@ public List computeResult() { } public void setVariables(Map variables) { - this.variables = Collections.unmodifiableMap(variables); + this.variables = new Document(variables); } public void validate(Document query) { diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStage.java index 01b5dc2a7..4778c21f5 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStage.java @@ -107,7 +107,7 @@ private List findLinkedDocuments(Object value) { } Object newValue = Utils.getSubdocumentValueCollectionAware(newDocument, connectFromField); enqueueValues(pending, newValue, current.depth() + 1); - Document result = newDocument.clone(); + Document result = newDocument.cloneDeeply(); if (depthField != null) { result.put(depthField, current.depth()); } diff --git a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStage.java b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStage.java index 5cbfe3659..37cf1a4c1 100644 --- a/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStage.java +++ b/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStage.java @@ -64,6 +64,8 @@ private List lookupValue(Object value) { value = null; } Document query = new Document(foreignField, value); - return collection.handleQueryAsStream(query).collect(toList()); + return collection.handleQueryAsStream(query) + .map(Document::cloneDeeply) + .toList(); } } diff --git a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java index 129e97745..4039bccf4 100644 --- a/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java +++ b/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java @@ -38,6 +38,155 @@ public abstract class AbstractAggregationTest extends AbstractTest { private static final int TEST_TIMEOUT_SECONDS = 30; + @ParameterizedTest + @MethodSource("pipelinesWithSharedNestedDocuments") + void testAggregationDoesNotModifyStoredDocuments(List stages) { + Document original = json("_id: 1, nested: {value: 1}, items: [{nested: {value: 1}}]"); + Document foreign = json("_id: 1, nested: {value: 1}"); + MongoCollection foreignCollection = db.getCollection("foreign"); + collection.insertOne(original); + foreignCollection.insertOne(foreign); + + List pipeline = new ArrayList<>(stages); + pipeline.add(json("$addFields: {nested: {value: 2}}")); + + List results = collection.aggregate(pipeline).into(new ArrayList<>()); + assertThat(results).hasSize(1); + assertThat(results.getFirst().get("nested")).isEqualTo(json("value: 2")); + assertThat(collection.find().first()).isEqualTo(original); + assertThat(foreignCollection.find().first()).isEqualTo(foreign); + } + + private static Stream> pipelinesWithSharedNestedDocuments() { + return Stream.of( + List.of(), + jsonList("$project: {nested: 1}"), + jsonList("$replaceRoot: {newRoot: {nested: '$nested'}}"), + jsonList("$unwind: '$items'", "$replaceRoot: {newRoot: '$items'}"), + jsonList("$group: {_id: null, nested: {$first: '$nested'}}"), + jsonList("$group: {_id: null, nested: {$last: '$nested'}}"), + jsonList("$group: {_id: null, nested: {$min: '$nested'}}"), + jsonList("$group: {_id: null, nested: {$max: '$nested'}}"), + jsonList("$group: {_id: null, nested: {$push: '$nested'}}", "$unwind: '$nested'"), + jsonList("$group: {_id: null, nested: {$addToSet: '$nested'}}", "$unwind: '$nested'"), + jsonList("$group: {_id: '$nested'}", "$replaceRoot: {newRoot: {nested: '$_id'}}"), + jsonList(""" + $bucket: { + groupBy: '$_id', + boundaries: [0, 2], + output: {nested: {$first: '$nested'}} + } + """), + jsonList( + """ + $lookup: { + from: 'foreign', + localField: '_id', + foreignField: '_id', + as: 'joined' + } + """, + "$unwind: '$joined'", "$replaceRoot: {newRoot: '$joined'}"), + jsonList( + "$lookup: {from: 'foreign', pipeline: [], as: 'joined'}", + "$unwind: '$joined'", "$replaceRoot: {newRoot: '$joined'}"), + jsonList( + """ + $lookup: { + from: 'foreign', + pipeline: [{$addFields: {nested: {value: 2}}}], + as: 'joined' + } + """, + "$unwind: '$joined'", "$replaceRoot: {newRoot: '$joined'}"), + jsonList( + """ + $graphLookup: { + from: 'foreign', + startWith: '$_id', + connectFromField: 'next', + connectToField: '_id', + as: 'joined' + } + """, + "$unwind: '$joined'", "$replaceRoot: {newRoot: '$joined'}") + ); + } + + @Test + void testFacetDoesNotModifyOtherBranchesOrStoredDocuments() { + Document original = json("_id: 1, nested: {value: 1}"); + collection.insertOne(original); + + List results = collection.aggregate(jsonList( + """ + $facet: { + modified: [{$addFields: {nested: {value: 2}}}], + original: [] + } + """ + )).into(new ArrayList<>()); + + assertThat(results).containsExactly(new Document("modified", List.of(json("_id: 1, nested: {value: 2}"))) + .append("original", List.of(original))); + assertThat(collection.find().first()).isEqualTo(original); + } + + @ParameterizedTest + @MethodSource("lookupPipelinesWithVariables") + void testLookupVariablesDoNotModifyOuterDocument(List lookupPipeline, List expectedJoined) { + Document original = json("_id: 1, items: [{value: 1}]"); + List foreign = List.of(json("_id: 10"), json("_id: 11")); + MongoCollection foreignCollection = db.getCollection("foreign"); + collection.insertOne(original); + foreignCollection.insertMany(foreign); + + Document lookup = new Document("from", "foreign") + .append("let", json("items: '$items'")) + .append("pipeline", lookupPipeline) + .append("as", "joined"); + + assertThat(collection.aggregate(List.of(new Document("$lookup", lookup)))) + .containsExactly(new Document(original).append("joined", expectedJoined)); + assertThat(collection.find().first()).isEqualTo(original); + assertThat(foreignCollection.find().sort(json("_id: 1"))).containsExactlyElementsOf(foreign); + } + + private static Stream lookupPipelinesWithVariables() { + return Stream.of( + Arguments.of(List.of(), List.of(json("_id: 10"), json("_id: 11"))), + Arguments.of(jsonList( + "$sort: {_id: 1}", + "$project: {items: '$$items'}", + "$unwind: {path: '$items', includeArrayIndex: 'items.index'}"), + List.of( + json("_id: 10, items: {value: 1, index: NumberLong(0)}"), + json("_id: 11, items: {value: 1, index: NumberLong(0)}"))) + ); + } + + @Test + void testUnwindArrayIndexDoesNotModifyStoredDocuments() { + Document original = json("_id: 1, items: [{value: 1}, {value: 2}]"); + collection.insertOne(original); + + assertThat(collection.aggregate(jsonList("$unwind: {path: '$items', includeArrayIndex: 'items.index'}"))) + .containsExactly( + json("_id: 1, items: {value: 1, index: NumberLong(0)}"), + json("_id: 1, items: {value: 2, index: NumberLong(1)}")); + assertThat(collection.find().first()).isEqualTo(original); + } + + @Test + void testNestedIdProjectionDoesNotModifyStoredDocuments() { + Document original = json("_id: {value: 1}, flag: 1"); + collection.insertOne(original); + + assertThat(collection.aggregate(jsonList("$project: {flag: 1, '_id.value': {$literal: 2}}"))) + .containsExactly(json("_id: {value: 2}, flag: 1")); + assertThat(collection.find().first()).isEqualTo(original); + } + @BeforeEach void dropAllDatabasesBeforeEachTest() { dropAllDatabases();