Meena Chaudhary
Meena Chaudhary

Reputation: 10665

Mapping Spring MongoDB AggregationResults ArrayList to List<POJO>

I need to return a List<AspectTemplate> from MongoDB aggregation operation.

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

In Spring MongoDB repository I am mapping AggregationResults like this

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

The raw results are

enter image description here

But the aspectTemplates.getMappedResults() returns the following enter image description here

enter image description here

How can I return allaspects ArrayList seen in raw results as List<AspectTemplate?

Upvotes: 1

Views: 2650

Answers (1)

Valijon
Valijon

Reputation: 13103

You need to add 2 extra operators into your pipeline and suggestion to modify your Entity class.

Entity

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

Aggregation

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

Upvotes: 1

Related Questions