Skip to content

Commit 63dd07b

Browse files
author
jmarkerink
committed
feat: optimized aggregation pipeline to use indexes when possible
1 parent e09dcfb commit 63dd07b

2 files changed

Lines changed: 13 additions & 0 deletions

File tree

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,15 @@ public static Aggregation fromPipeline(List<Document> pipeline, DatabaseResolver
189189
}
190190

191191
private List<Document> runStages() {
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+
}
192201
return runStages(collection.queryAllAsStream());
193202
}
194203

core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MatchStage.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,8 @@ public String name() {
2424
public Stream<Document> apply(Stream<Document> stream) {
2525
return stream.filter(document -> queryMatcher.matches(document, query));
2626
}
27+
28+
public Document getQuery() {
29+
return query;
30+
}
2731
}

0 commit comments

Comments
 (0)