[英]spring data mongodb group by
I am using spring data Mongodb in my project and refer the below classes for my query on grouping the results: 我在项目中使用Spring数据Mongodb,并在查询结果时参考以下类:
Student class: 学生班:
@Document(collection = "student")
public class Student {
@Id
private String id;
private String firstName;
private String lastName;
//other fields
//getters & setters
}
StudentResults (dto): 学生成绩(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 class: 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;
}
}
Using the above code, I am able to retrieve the List<String> studentIds
successfully, but I need to retrieve List<Student> students
using Aggregation.group()
? 使用上面的代码,我能够成功检索
List<String> studentIds
,但是我需要使用Aggregation.group()
检索List<Student> students
? Can you help? 你能帮我吗?
Change your TypedAggregation
part to below and add students
field to StudentResults
您更改
TypedAggregation
部分的下方,添加students
场StudentResults
TypedAggregation<Student> studentAggregation = Aggregation.newAggregation(Student.class,
Aggregation.group("firstName").
push("$$ROOT").as("students"));
$$ROOT will push the whole document. $$ ROOT将推送整个文档。
Update: 更新:
TypedAggregation<Student> studentAggregation = Aggregation.newAggregation(Student.class,
Aggregation.group("firstName").
push(new BasicDBObject
("_id", "$_id").append
("firstName", "$firstName").append
("lastName", "$lastName")).as("students"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.