복붙노트

[SPRING] 봄 데이터 몽고 그룹

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;
    }
}

학생 ServiceImpl 클래스 :

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 studentId를 성공적으로 가져올 수 있지만 Aggregation.group ()을 사용하여 List 학생을 검색해야합니까? 도울 수 있니?

해결법

  1. ==============================

    1.TypedAggregation 부분을 아래로 변경하고 StudentResults에 students 필드를 추가하십시오.

    TypedAggregation 부분을 아래로 변경하고 StudentResults에 students 필드를 추가하십시오.

     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"));
    
  2. from https://stackoverflow.com/questions/42814325/spring-data-mongodb-group-by by cc-by-sa and MIT license