代码之家  ›  专栏  ›  技术社区  ›  Michal

仅当MongoDB中的外部字段不为空时查找

  •  0
  • Michal  · 技术社区  · 7 年前

    我收藏了一些文章和评论。评论可能有 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 ?

    0 回复  |  直到 7 年前
        1
  •  1
  •   Ashh    7 年前

    可以使用下面的聚合与MangoDB 三点六 及以上

    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"
      }}
    ])
    
    推荐文章