2017-08-22 2 views
0

Ich brauche die durchschnittliche Dauer aller durchgeführten Iterationen. Ich habe die Einheit Einheit, die ich weiter unten erklären:Get einfache Durchschnitt aus Sammlung mit Spring Data MongoDB

@Document(collection = IterationEntity.COLLECTION_NAME) 
public class IterationEntity { 

    public final static String COLLECTION_NAME = "iterations"; 

    @Id 
    private ObjectId id; 

    @Field("start_date") 
    private Date startDate; 

    @Field("finish_date") 
    private Date finishDate; 

    @Field("duration") 
    private Long duration; 

    @Field("total_tasks") 
    private Integer totalTasks = 0; 

    @Field("total_failed_tasks") 
    private Integer totalFailedTasks = 0; 

    @Field("total_comments") 
    private Integer totalComments = 0; 

    @Field("tasks") 
    @DBRef 
    @CascadeSave 
    private Set<TaskEntity> tasks = new HashSet<>(); 

} 

ich eine benutzerdefinierte Repository-Methode implementiert haben diese Operation auszuführen, aber ich erhalte eine Fehlermeldung, wenn ich das Ergebnis.

@Override 
    public Long getAvgDuration() { 

     GroupOperation avgOperation = Aggregation.group() 
      .sum("duration") 
       .as("total_duration") 
      .avg("total_duration") 
       .as("avg_duration"); 

     Aggregation aggregation = newAggregation(IterationEntity.class, avgOperation); 

     return mongoTemplate.aggregate(aggregation, IterationEntity.COLLECTION_NAME, Long.class).getUniqueMappedResult(); 

    } 

Wenn das Verfahren ausgeführt wird, ich diese Ausnahme erhalten:

org.springframework.data.mapping.model.MappingException: No mapping metadata found for java.lang.Long 

Vielen Dank im Voraus.

+2

In oben Aggregationsanfrag, kehren Sie beide Summe & Durchschnitt, während Sie lange als Klassentyp funktionieren mongoTemplate.aggregate gegeben haben. Ich denke, das ist das Problem – Afridi

Antwort

1

Um das Aggregationsergebnis korrekt zuzuordnen, muss es einem Domänen-Typ zugeordnet werden oder einfach Document zurückgegeben werden.
Etwas wie unten sollte tun, was Sie suchen.

class AggResult { 
    @Field("total_duration") Long duration; 
    @Field("avg_duration") Double avgDuration; 
} 

return template 
    .aggregate(aggregation, COLLECTION_NAME, AggResult.class) 
    .getUniqueMappedResult() 
    .getAvgDuration(); 
+0

Es funktioniert !!. Ich danke dir sehr. –