【问题标题】:spring data mongodb group bySpring Data MongoDB Group by
【发布时间】:2017-08-06 11:04:25
【问题描述】:

我在我的项目中使用 Spring Data Mongodb,并参考以下类来查询我对结果分组的查询:

学生班:

@Document(collection = "student")
public class Student {

    @Id
    private String id;

    private String firstName;

    private String lastName;

    //other fields

    //getters & setters

}

学生成绩 (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&lt;String&gt; studentIds,但是我需要使用Aggregation.group()检索List&lt;Student&gt; students?你能帮忙吗?

【问题讨论】:

    标签: java spring mongodb spring-data-mongodb


    【解决方案1】:

    将您的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"));
    

    【讨论】:

    • 不使用$$ROOT还有其他选择吗?
    • 好的,谢谢,如何在上面添加包含多个字段的分组方式,即名字和姓氏?
    • Np。你可以试试Aggregation.group("firstName", "lastName")
    • 尝试推送列,但多次获取列值(等于计数中的次数){ "group": "[ \"test\" , \"test\ " , \"test\"]", "count": 3 }
    • @Anand 使用 addToSet 获取唯一值而不是推送。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多