2017-03-15 3 views
0

Ich bin mit Federdaten MongoDB in meinem Projekt und die folgenden Klassen für meine Abfrage beziehen sich die Ergebnisse auf die Gruppierung:Federdaten mongodb Gruppe von

Student-Klasse:

@Document(collection = "student") 
public class Student { 

    @Id 
    private String id; 

    private String firstName; 

    private String lastName; 

    //other fields 

    //getters & setters 

} 

StudentResults (dto):

public class StudentResults { 

    private String firstName; 

    private List<String> studentIds; //I need List<Student> here 

    public String getFirstName() { 
     return firstName; 
    } 

    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 

    public List<String> getStudentIds() { 
     return studentIds; 
    } 

    public void setStudentIds(List<String> studentIds) { 
     this.studentIds = studentIds; 
    } 
} 

StudentServiceImpl Klasse:

public class StudentServiceImpl implements StudentService { 
    @Autowired 
    private MongoTemplate mongoTemplate; 

    public List<StudentResults> findStudentsGroupByFirstName() { 
     TypedAggregation<Student> studentAggregation = 
       Aggregation.newAggregation(Student.class, 
       Aggregation.group("firstName"). 
       addToSet("id").as("studentIds"), 
       Aggregation.project("studentIds"). 
       and("firstName").previousOperation()); 

     AggregationResults<StudentResults> results = mongoTemplate. 
      aggregate(studentAggregation, StudentResults.class); 

     List<StudentResults> studentResultsList = results.getMappedResults(); 

     return studentResultsList; 
    } 
} 

den obigen Code verwenden, kann ich die List<String> studentIds erfolgreich abzurufen, aber ich brauche List<Student> students mit Aggregation.group() abzurufen? Kannst du helfen?

Antwort

4

auf unter und füge students Feld StudentResults

TypedAggregation<Student> studentAggregation = Aggregation.newAggregation(Student.class, 
       Aggregation.group("firstName"). 
       push("$$ROOT").as("students")); 

$$ROOT wird das gesamte Dokument schieben ändern TypedAggregation Teil.

Update:

TypedAggregation<Student> studentAggregation = Aggregation.newAggregation(Student.class, 
       Aggregation.group("firstName"). 
       push(new BasicDBObject 
         ("_id", "$_id").append 
         ("firstName", "$firstName").append 
         ("lastName", "$lastName")).as("students")); 
+0

Gibt es eine andere Alternative ohne Verwendung von '$$ ROOT'? – developer

+0

Sie können sie immer manuell zuordnen. Diese Option eingeschlossen. – Veeram

+0

Okay, danke, wie füge ich Gruppen mit mehreren Feldern zu den obigen hinzu, d. H. Vorname und Nachname? – developer

Verwandte Themen