【发布时间】:2017-08-06 11:04:25
【问题描述】:
我在我的项目中使用 Spring Data Mongodb,并参考以下类来查询我对结果分组的查询:
学生班:
@Document(collection = "student")
public class Student {
@Id
private String id;
private String firstName;
private String lastName;
//other fields
//getters & setters
}
学生成绩 (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?你能帮忙吗?
【问题讨论】:
标签: java spring mongodb spring-data-mongodb