0

I want to map the results of an aggregation to an POJO without iterating through the raw results. The POJO is a field in the Collection on which I'm running the aggregation.

MatchOperation match = match(Criteria.where("drill").is(drill));
SortOperation sort = sort(DESC, "creationDate");
GroupOperation group = group("athlete").first("athlete").as("athlete");
LimitOperation limit = limit(10);
ProjectionOperation project = project("athlete");

Aggregation aggregation = newAggregation(match, sort, group, limit, project);
AggregationResults<Athlete> results = mongoTemplate.aggregate(aggregation, DrillResultInfo.class, Athlete.class);
List<Athlete> mappedResult = results.getMappedResults();

It returns the correct number of objects, but they have as the id the map of the object and the other properties are null.

The result:

id: { "_id" : { "$oid" : "57cd46780348276373579821"} , "_class" : "Athlete" , "firstName" : "Jenny" , "lastName" : "Smith" ....}

The rest of the properties are null.

The Collection:

public class DrillResultInfo {

@Id
private String id;
private Long resultId;

@DBRef
private Athlete athlete;
@DBRef
private Drill drill;
....
}

(.... represents left out data)

Update:

I've made some updates to the code to get it to work:

List<Athlete> respone = new ArrayList<>();
MatchOperation match = match(Criteria.where("drill").is(drill));
SortOperation sort = sort(DESC, "creationDate");
GroupOperation group = group("athlete");
LimitOperation limit = limit(5);
SkipOperation skip = skip(skipElements);
ProjectionOperation project = project("_id");

TypedAggregation<DrillResultInfo> agg = newAggregation(DrillResultInfo.class, match, sort, group, skip, limit, project);
AggregationResults<Object> results = mongoTemplate.aggregate(agg, Object.class);
List<Object> mappedResult = results.getMappedResults();

for (Object obj : mappedResult) {
    Athlete ath = (Athlete) ((LinkedHashMap) obj).get("_id");
    respone.add(ath);
}

return respone;

I would like to get rid of that for.

Dr.Agos
  • 2,229
  • 2
  • 15
  • 17
  • I could be wrong, but can be due this `project("athlete");` thus projecting only `athlete` field? – nurgasemetey Sep 29 '16 at 13:23
  • I've done some updates to the code. I've tried to project statements without any success. Also I've tried without the project operation, but it creates the Athlete object with the value of the id equal to the entire result of the aggregation. – Dr.Agos Sep 29 '16 at 14:11

0 Answers0