spring数据mongodb group by

我在我的项目中使用spring数据Mongodb,并在下面的类中引用我的查询来对结果进行分组:

学生class:

@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 studentIds; //I need List here public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public List getStudentIds() { return studentIds; } public void setStudentIds(List studentIds) { this.studentIds = studentIds; } } 

StudentServiceImpl类:

 public class StudentServiceImpl implements StudentService { @Autowired private MongoTemplate mongoTemplate; public List findStudentsGroupByFirstName() { TypedAggregation studentAggregation = Aggregation.newAggregation(Student.class, Aggregation.group("firstName"). addToSet("id").as("studentIds"), Aggregation.project("studentIds"). and("firstName").previousOperation()); AggregationResults results = mongoTemplate. aggregate(studentAggregation, StudentResults.class); List studentResultsList = results.getMappedResults(); return studentResultsList; } } 

使用上面的代码,我能够成功检索List studentIds ,但我需要使用Aggregation.group()检索List students ? 你能帮我吗?

TypedAggregation部分更改为下方,并将StudentResults字段添加到StudentResults

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

$$ ROOT将推送整个文档。

更新:

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