我有一個這樣的模型
Story:
- id
Chapter:
- id
- story_id
Comment:
- id
- chapter_id
Reply:
- id
- 評論_id
我需要計算一個故事有多少條評論,這意味著要搜索一個故事的所有章節,然后計算指向每個章節的所有評論,然后搜索每個評論的所有回復,并添加到數字中。有什么方法可以用一個單一的查詢做到這一點嗎?在SQL中,我通常會連接所有的表,然后計算結果,但我不確定這是否能在Mongo中實作。
uj5u.com熱心網友回復:
對每個集合使用聚合$lookup,然后$unwind。
之后按id分組(指故事id)
https://mongoplayground.net/p/zMHas1JKjdh
db.Story.aggregate( [
{
"$lookup"/span>: {
"from": "Chapter",
"localField": "id",
"foreignField": "story_id",
"as": "chapter".
}
},
{
"$unwind": "$chapter": "$chapter".
},
{
"$lookup": {
"from": "Comment",
"localField": "chapter.id"。
"foreignField": "chapter_id",
"as": "comment".
}
},
{
"$unwind": "$comment": "$comment".
},
{
"$group": {
"_id": "$id",
"count": {
"$sum": "1
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/307949.html
標籤:
上一篇:MongoDB32位GUI客戶端
