Spring Mongo > 如何从聚合中获取列表聚合操作

Spring Mongo > How to get list AggregationOperations from Aggregation

我有一个接收 Aggregation aggregation 作为参数的函数。

我想从 aggregation 获得所有 AggregationOperation。有什么办法吗?

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

我的目的是另一个 Aggregation 我的习惯 MatchAggregation

Aggregation 有一个 属性 operations,它将为您提供 Aggregation 中的所有应用操作。

 protected List<AggregationOperation>   allOperations = aggregation.operations ;

将为您提供所有应用操作。

简短回答:不,没有好的方法。

没有 'easy' 从 Aggregation 实例外部获取 AggregationOperation 列表的方法 - operations 是 [=11 的受保护 属性 =] class.

你可以很容易地通过反射得到它,但这样的代码会很脆弱并且维护起来很昂贵。 属性 可能有充分的理由受到保护。你可以在 Spring-MongoDB's JIRA 中询问这个问题。我认为有另一种方法可以解决这个问题。

您当然可以更改您的方法以将 AggregationOperation 的集合作为参数,但是您的 post 中的信息太少无法说明此解决方案是否适用于您的情况。

您可以创建自己的自定义聚合实现,方法是对聚合进行子类化以访问受保护的操作字段。

类似于

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);
 }