參見:原文鏈接: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; }