我收藏了一些文章和评论。评论可能有
articleId
(这是对文章的答复)或
parentId
(这是对另一条评论的回应)。只有两个层次,回答另一个评论不能有答案。
// 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": [] }
在第二秒之后
查找
(回复评论):
{
"_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是
not null
?