我收藏了文章和评论。评论可能包含articleId
(是对文章的答复)或parentId
(是对另一条评论的答复)。只有2个级别,对其他评论的回答不能有答案。
// articles
{ "_id": 100, "text": "Article text" }
// comments
{ "_id": 1, "text": "First text", "articleId": 100 },
{ "_id": 2: "text": "Second text", "articleId": 100 },
{ "_id": 3, "text": "Third text", "parentId": 2 }
我想找到所有文章,文章的评论和答案以进行评论。
db.getCollection("articles").aggregate([
{ "$match": {} },
// Lookup comments of article.
{ "$lookup": { "from": "comments", "localField": "_id", "foreignField": "parentId", as: "comments" } },
{ "$unwind": { "path": "$comments", "preserveNullAndEmptyArrays": true } },
// Lookup answers to comments. There I need lookup only when foreignField is not null.
{ "$lookup": { "from": "comments", "localField": "comments._id", "foreignField": "parentId", "as": "comments.answers" } },
{ "$group": { "_id": "$_id", "comments": { "$push": "$comments" }, "text": { "first": "$text" } }
])
如果文章有一些评论,它会起作用。但是如果没有,那么在第一篇lookup
(文章评论)之后,文章看起来像这样(可以使用空数组):
{ "_id": 100, "text": "Article text", "comments": [] }
第二lookup
(评论的答案)之后:
{
"_id": 100,
"text": "Article text",
"comments": [{
"answers": [
{ "_id": 1, "text": "First text", "articleId": 100 },
{ "_id": 2: "text": "Second text", "articleId": 100 }
]
}]
}
即使没有评论,评论也有一些答案。我认为这是因为localField comments._id
是null
,这些答案中的foreignField parentId
也是null
。仅当foreignField为not null
时,有什么方法可以查找吗?
答案 0 :(得分:1)
您可以在mongodb 3.6 及更高版本
中使用以下聚合Article.aggregate([
{ "$lookup": {
"from": "comments",
"let": { "articleId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$articleId", "$$articleId" ] } } },
{ "$lookup": {
"from": "comments",
"let": { "commentId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$parentId", "$$commentId" ] } } }
],
"as": "answers"
}}
],
"as": "comments"
}}
])