Spring Mongo > How to get list AggregationOperations from Aggregation

Viewed 901

I have a function that receive an Aggregation aggregation as a param.

I would like to get all AggregationOperation from aggregation. Is there any way to do it?

public Aggregation newCustomAggregation(Aggregation aggregation, Criteria c) {
    // How to get list operation aggregation there?
    listOperation.push(Aggregation.match(c));
    return Aggregation
            .newAggregation(listOperations);
}

My purpose is new another Aggregation with my custom MatchAggregation.

3 Answers

You can create your own custom aggregation implementation by subclassing the aggregation to access the protected operations field.

Something like

public class CustomAggregation extends Aggregation {
      List<AggregationOperation> getAggregationOperations() {
      return operations;
   }
}

public Aggregation newCustomAggregation(Aggregation aggregation, Criteria c) {
     CustomAggregation customAggregation = (CustomAggregation) aggregation;
     List<AggregationOperation> listOperations = customAggregation.getAggregationOperations();
     listOperations.add(Aggregation.match(c));
     return Aggregation .newAggregation(listOperations);
 }

Short answer: No, there's no GOOD way to do it.

There is no 'easy' way of getting the AggregationOperation list from outside an Aggregation instance - operations is a protected property of Aggregation class.

You could easily get it with reflection but such code would be fragile and expensive to maintain. Probably there's a good reason for this property to remain protected. You could ask about this in Spring-MongoDB's JIRA. I assume that there is an alternative approach to this.

You could of course change your method to take a collection of AggregationOperation as parameter but there's too liitle information in your post to say if this solution is feasible in your case.

Aggregation has a property operations which will give you all applied operation in Aggregation.

 protected List<AggregationOperation>   allOperations = aggregation.operations ;

will give you all applied operations.

Related