2017-03-15 111 views
0

我用我的項目春季數據的MongoDB並將有關分組的結果如下班我的查詢:春天數據的MongoDB組由

Student類:

@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類:

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; 
    } 
} 

使用上面的代碼,我能夠檢索List<String> studentIds成功,但我需要使用Aggregation.group()檢索List<Student> students?你能幫我嗎?

回答

4

TypedAggregation部分更改爲以下和students字段添加到StudentResults

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

$$ROOT將推動整個文檔。

更新:

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

有沒有使用'$$ ROOT'任何其他選擇嗎? – developer

+0

您可以隨時手動映射它們。包括那個選項。 – Veeram

+0

好的,謝謝,我該如何添加多個字段的組合,即firstname和lastname? – developer