【问题标题】:Mapping Spring MongoDB AggregationResults ArrayList to List<POJO>将 Spring MongoDB AggregationResults ArrayList 映射到 List<POJO>
【发布时间】:2020-03-23 09:41:38
【问题描述】:

我需要从 MongoDB 聚合操作返回 List&lt;AspectTemplate&gt;

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

原始结果是

aspectTemplates.getMappedResults() 返回以下内容

如何将原始结果中的allaspects ArrayList 返回为List&lt;AspectTemplate

【问题讨论】:

  • 你的ProjectionOperation需要返回AspectTemplate字段(id, title, options),但它返回allaspects
  • @Valijon 你能输入一小段代码吗?如何将当前投影转换为返回字段。
  • 当然,但我需要知道allaspects 字段后面隐藏的是什么:D。如果您在投影之前在 MongoDB CLI 中运行聚合,您会得到什么 JSON? (请在您的问题中发布)
  • @Valijon 添加了allaspects 元素的截图

标签: java spring mongodb spring-boot spring-mongodb


【解决方案1】:

您需要在管道中添加 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多