如何使用MongoDB中的多表關聯查詢($lookup) 示例


簡單了解下mysql 如何實現  多表關聯?

mysql 使用兩個表關聯用 A表 left join B表  on  A.id=B.id  

注 :A表為主表

 

 

 

mongdb 因為是文檔存儲的所以和MySQL有些許不一樣。

db.comment.aggregate([
{
$lookup:
{
from: "reply",
localField: "_id",
foreignField: "commentid",
as: "reply"
}
},
{
$lookup:
{
from: "service_provider_signed_money",
localField: "userid",
foreignField: "user_id",
as: "money"
}
}
])

 

 

 

 

 

 

 

 

 

 

 

 

看看我的示例:

這里我會先創建兩個表:Reply(回復表)

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection="reply")
public class Reply {
@Id
private String _id;
private String contentTxt;
private String userid;
private String parentid;
private String createdatetime;
//原因
private String reason;
//評論id
private String commentid;
}














Comment(評論表)
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection="comment")
public class Comment implements Serializable {
@Id
private String _id;
private String articleid;
private String content;
private String userid;
private String nickname;
private String createdatetime;
private Integer likenum; //點贊數
private Integer replynum;//回復數
private Integer state; //狀態
private String parentid;
}
















返回參數類:
@Data
public class ReplyCommentDto {

private String _id;
private String articleid;
private String content;
private String userid;
private String nickname;
private String createdatetime;
private Integer likenum; //點贊數
private Integer replynum;//回復數
private Integer state; //狀態
private String parentid;
//對應上面的回復表
private Reply reply;
}















Java 代碼:
@Override
public List<ReplyCommentDto> getReplyComment(String content, int pageNum, int pageSize) {
// 構建 Aggregation:添加查詢條件
Aggregation aggregation = Aggregation.newAggregation(
// 關聯member表
Aggregation.lookup(
"reply", // 從表表名
"_id", // 如comment被查詢主表的_id,相對於reply表的外鍵
"commentid", // 如reply從表的外鍵commentid,相對於comment表的主鍵
"reply" // 聯合查詢出的別名,用於多條件查詢表明前綴,相當於SQL中的臨時表名
),
// ============================================= 以上內容可舉一反三 =======================
// 查詢條件
null == content || "".equals(content.trim())
?
Aggregation.match(
Criteria.where("content").nin("") // 店鋪狀態: 1:已審核
// 添加member表查詢條件,如用戶手機號,此處可舉一反三
)
:
Aggregation.match(
Criteria.where("content").regex(content)

),
// 分頁:頁碼
Aggregation.skip(Long.valueOf(pageNum)),
// 分頁:條數
Aggregation.limit((long) pageSize),
// 排序
Aggregation.sort(Sort.Direction.DESC,"createdatetime")
);
// 執行查詢,這里的shop必須是查詢的主表名
AggregationResults<ReplyCommentDto> results = mongoTemplate.
aggregate(aggregation, "comment", ReplyCommentDto.class);
return results.getMappedResults();
}
































注意:
mongodb 字段類型 問題 主鍵 默認為:對象id 字段類型不一致可能會導致查不出來


免責聲明!

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



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