Skip to content

Commit 3f2cbd1

Browse files
author
jmarkerink
committed
feat: optimized aggregation pipeline to use indexes when possible
1 parent 2809f24 commit 3f2cbd1

1 file changed

Lines changed: 10 additions & 5 deletions

File tree

core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -189,11 +189,16 @@ public static Aggregation fromPipeline(List<Document> pipeline, DatabaseResolver
189189
}
190190

191191
private List<Document> runStages() {
192-
return stages.stream()
193-
.filter(stage -> stage instanceof MatchStage)
194-
.findFirst()
195-
.map(match -> runStages(collection.handleQueryAsStream(((MatchStage) match).getQuery())))
196-
.orElseGet(() -> runStages(collection.queryAllAsStream()));
192+
// Only apply index optimization if there are no variables to inject
193+
// Variables need to be added to documents before $match can evaluate them
194+
if (!hasVariables()) {
195+
return stages.stream()
196+
.filter(stage -> stage instanceof MatchStage)
197+
.findFirst()
198+
.map(match -> runStages(collection.handleQueryAsStream(((MatchStage) match).getQuery())))
199+
.orElseGet(() -> runStages(collection.queryAllAsStream()));
200+
}
201+
return runStages(collection.queryAllAsStream());
197202
}
198203

199204
public List<Document> runStages(Stream<Document> stream) {

0 commit comments

Comments
 (0)