【发布时间】:2019-07-11 01:44:56
【问题描述】:
我收藏了文章和 cmets。评论可能有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 }
我想找到所有文章、cmets文章和答案对cmets。
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" } }
])
如果文章有一些 cmets,它会起作用。但是如果不是,在第一篇lookup(文章的cmets)之后的文章看起来是这样的(空数组也可以):
{ "_id": 100, "text": "Article text", "comments": [] }
第二次之后lookup(对 cmets 的回答):
{
"_id": 100,
"text": "Article text",
"comments": [{
"answers": [
{ "_id": 1, "text": "First text", "articleId": 100 },
{ "_id": 2: "text": "Second text", "articleId": 100 }
]
}]
}
即使没有 cmets,也有一些 cmets 的答案。我认为这是因为 localField comments._id 是 null 和 foreignField parentId 这些答案也是 null。有没有办法只在foreignField为not null时查找?
【问题讨论】:
标签: mongodb aggregation-framework