时间:2017-03-15 15:37:35

标签: java spring mongodb spring-data-mongodb

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

学生班:

@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,但我需要使用List<Student> students检索Aggregation.group()?你能帮忙吗?

1 个答案:

答案 0 :(得分: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"));