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
?你能帮我吗?
有没有使用'$$ ROOT'任何其他选择吗? – developer
您可以随时手动映射它们。包括那个选项。 – Veeram
好的,谢谢,我该如何添加多个字段的组合,即firstname和lastname? – developer