我需要从MongoDB聚合操作返回List<AspectTemplate>

public class AspectTemplate {
  private ObjectId id;
  private String title;
  private List<String> options;
}


在Spring MongoDB存储库中,我这样映射AggregationResults

ProjectionOperation projectOperation = Aggregation.project()
            .and("easpects").concatArrays("iaspects").as("allaspects").andExclude("_id");
AggregationResults<AspectTemplate> aspectTemplates = this.mongoOperations.aggregate(Aggregation.newAggregation(
            matchOperation,
            lookupOperation, projectOperation
    ), COLLECTION_NAME, AspectTemplate.class);

return aspectTemplates.getMappedResults();


原始结果是

java - 将Spring MongoDB AggregationResults ArrayList映射到List &lt;POJO&gt;-LMLPHP

但是aspectTemplates.getMappedResults()返回以下内容
java - 将Spring MongoDB AggregationResults ArrayList映射到List &lt;POJO&gt;-LMLPHP

java - 将Spring MongoDB AggregationResults ArrayList映射到List &lt;POJO&gt;-LMLPHP

如何返回在原始结果中显示为allaspectsList<AspectTemplate ArrayList?

最佳答案

您需要在管道中添加2个额外的运算符,并建议您修改Entity类。

实体

@Document(collection = "COLLECTION_NAME")
public class AspectTemplate {
  @Id
  private ObjectId id;
  private String title;
  private List<String> options;
}


聚合

ProjectionOperation projectOperation = Aggregation.project()
    .and("easpects").concatArrays("iaspects").as("allaspects")
    .andExclude("_id");
UnwindOperation unwind = Aggregation.unwind("allaspects");
ReplaceRootOperation replaceRoot = Aggregation.replaceRoot("allaspects");
AggregationResults<AspectTemplate> aspectTemplates = mongoOperations.aggregate(Aggregation.newAggregation(
            matchOperation,
            lookupOperation, projectOperation,
            unwind, replaceRoot
    ), mongoOperations.getCollectionName(AspectTemplate.class), AspectTemplate.class);

return aspectTemplates.getMappedResults();

09-26 04:12