仅当mongoDB中的外部字段不为空时才进行查找
我收集了一些文章和评论。评论可能有articleId,它是对文章的回答,或者parentId,它是对另一个评论的回答。只有两个级别,其他评论的答案不能有答案仅当mongoDB中的外部字段不为空时才进行查找,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我收集了一些文章和评论。评论可能有articleId,它是对文章的回答,或者parentId,它是对另一个评论的回答。只有两个级别,其他评论的答案不能有答案 // articles { "_id": 100, "text": "Article text" } // comments { "_id": 1, "text": "First text", "articleId": 100 }, { "_id": 2: "text": "Second text", "articleId": 100
// 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" } }
])
如果这篇文章有一些评论就行了。但如果不是,在第一次查找文章后,文章的注释看起来这个空数组是可以的:
{ "_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注释.\u id为null,这些答案的foreignField parentId也为null。只有当foreignField不为空时,才有方法查找吗 您可以在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"
}}
])