Skip to content
Advertisement

Aggregation with multiple criteria

I want to perform aggregation using multiple criteria. The problem is that I don’t know how to pass multiple criteria. Do I declare multiple Match operation like below?

MatchOperation matchOperation1 = Aggregation.match(criteria);
MatchOperation matchOperation2 = Aggregation.match(criteria2);

And if yes, then how do I pass them to the aggregation method? I thought that it should be possible to create a MatchOperation that adheres in multiple criteria but I have not found such an example online.

Advertisement

Answer

Do I declare multiple Match operation like below?

MatchOperation matchOperation1 = Aggregation.match(criteria); 
MatchOperation matchOperation2 = Aggregation.match(criteria2);

The Criteria class has an and method, which allows combining two conditions. For example, consider the three documents:

{ _id: 1, size: 10, color: "blue" }
{ _id: 2, size: 12, color: "red" }
{ _id: 3, size: 8, color: "blue" }

The aggregation match stage is defined as follows:

Aggregation.match(Criteria.where("size").gt(new Integer(8))
                            .and("color").is("blue")
)

This returns the document with _id: 1.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement