springboot集成MongoDB實現多表查詢

小編真的是~有點兒時間都獻給工作了,這不這兩天兒又弄了個類似論壇的東西,用的MongoDB數據庫,帖子評論和回覆分別弄了兩張表~下面貼代碼,Spring Data Mongodb(小編弄了兩張表的聯查,剩下的閒暇時間再弄)

首先pom.xml裏要有Spring Data Mongodb的配置,如果要是在官網生成項目的話會直接帶出來

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
//這裏面我沒用@Id,因爲這個自動生成的id查詢後傳遞到前臺就變成了MongoDB:ObjectID本身的樣子了,前臺直接獲取獲不到,這裏在set數據時我直接給id設置uuid了
//帖子評論表
@Data
@Document(collection = "DirectTrainPostLeaveMessage")
public class DirectTrainPostLeaveMessage {
    private String id;
    private String breedId;   //主題id(什麼品種)
    private String postId;   //帖子id
    private String postTopic;   //帖子主題
    private String postTitle;   //帖子標題
    private String leaveMessage;   //留言內容
    private String leaveMessageId;   //留言人id
    private String leaveMessageMan;   //留言人
    private String leaveMessageTime;   //留言時間
    private int leaveMessagePraise;   //留言點贊
}

//回覆評論表
@Data
@Document(collection = "DirectTrainPostLeaveMessageComment")
public class DirectTrainPostLeaveMessageComment {
    private String id;
    private String leaveId;   //留言id
    private String leaveMessageMan;   //留言人
    private String comment;   //評論內容
    private String commentId;   //評論人id
    private String commentMan;   //評論人
    private String commentTime;   //評論時間
    private int commentPraise;   //評論點贊
}

訪問controller方法獲取數據

@RequestMapping(value = {"/getLeaveMessage"}, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public BaseResult getLeaveMessage () {
    LookupOperation lookupOperation = LookupOperation.newLookup().from("DirectTrainPostLeaveMessageComment")   //從表名
                .localField("_id")   //主表關聯字段
                .foreignField("leaveId")   //從表關聯字段
                .as("CommentList");   //查詢結果名
    //匹配id條件
    MatchOperation matchOperation = new MatchOperation(Criteria.where("postId").is(postId));
    //按回帖時間排序
    SortOperation sortOperation = new SortOperation(Sort.by(Sort.Order.desc("leaveMessageTime")));
    Aggregation aggregation = Aggregation.newAggregation(lookupOperation);
    List<Map> result = mongoTemplate.aggregate(aggregation, "DirectTrainPostLeaveMessage", Map.class).getMappedResults();
    //DirectTrainPostLeaveMessage是主表名
    return BaseResult.ok(result);
}

 上面的java語句切換成MongoDB命令是這樣兒滴~(要說這個nosql剛剛寫起來也是蹩手)

db.DirectTrainPostLeaveMessage.aggregate([   //db後面的是主表名
    {
        $lookup: 
        {
            from: "DirectTrainPostLeaveMessageComment",   //從表名
            localField: "_id",   //主表關聯字段
            foreignField: "leaveId",   //從表關聯字段
            as: "CommentList"   //查詢結果名
        }
    },
    {
        $match:
	{
	    postId : "5e85a5d5e79d53eaacce974c"
	}
    },
	{
	$sort:
	{
	    leaveMessageTime : -1   //排序:升序:1,降序:-1
	}
    }
])

數據返回效果:

頁面渲染效果:

over~有不足還請指教~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章