MongoDB Aggregation - How can i apply query expression into match stage using spring-data-mongodb?
The query can be passed on as an expression into Project pipeline stage and the result can then be passed onto Match pipeline stage to evaluate true/false.
Similar to somewhat this answer here: Spring data mongo: Projection not working when path includes a key of a HashMap
You can implement your own AggregationOperation
to deal with your varying conditions. Haven't tried my own code, but it should be something like that:
AggregationOperation myMatch (List<Document> conditions) {
return new AggregationOperation() {
@Override
public String getOperator() {
return "$match";
}
@Override
public Document toDocument(AggregationOperationContext context) {
return new Document("$match",
new Document("$expr",
new Document("$and", conditions)
)
);
}
};
}
and call it that way (to match your question query):
void callMyMatch() {
myMatch(List.of(
new Document("$gt", List.of("$attributes.age", 40)),
new Document("$eq", List.of("$attributes.name", "Name2"))
));
}