【问题标题】:Lookup only if foreign field is not null in mongoDB仅当外部字段在 mongoDB 中不为空时查找
【发布时间】: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(对 cme​​ts 的回答):

{
    "_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._idnull 和 foreignField parentId 这些答案也是 null。有没有办法只在foreignField为not null时查找?

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案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"
      }}
    ])
    

    【讨论】:

      猜你喜欢
      • 2020-03-13
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2019-07-04
      • 2011-08-24
      • 2020-08-21
      相关资源
      最近更新 更多