MongoDB實現聚合(多表聯查)springBoot


參見:原文鏈接:https://blog.csdn.net/weixin_44530530/java/article/details/91901631

 

依賴:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
 </dependency>

 

兩表聯查
 /**
     * 兩表聯查
     *
     * @return
     */
    @Override
    public Object findStudentAndGrade() {
        LookupOperation lookupOperation=LookupOperation.newLookup().
                from("grade").  //關聯從表名
                localField("gradeId").     //主表關聯字段
                foreignField("_id").//從表關聯的字段
                as("GradeAndStu");   //查詢結果名
//帶條件查詢可以選擇添加下面的條件
//       Criteria criteria=Criteria.where("studenAndgrade").not().size(0);   //只查詢有結果的學生
//        Criteria qqq=Criteria.where("name").regex("文");//只查詢名字中帶有文的
 //       AggregationOperation match1= Aggregation.match(qqq);
//        AggregationOperation match = Aggregation.match(criteria);
//        Aggregation counts = Aggregation.newAggregation(match1,lookupOperation,match).;
       Aggregation aggregation=Aggregation.newAggregation(lookupOperation);
        List<Map> results = mongoTemplate.aggregate(aggregation,"student", Map.class).getMappedResults();
        //上面的student必須是查詢的主表名
        System.out.println(JSON.toJSONString(results));
        return results;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM