我需要从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();
原始结果是
但是
aspectTemplates.getMappedResults()
返回以下内容如何返回在原始结果中显示为
allaspects
的List<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();