Mongodb aggregation lookup with conditions

后端 未结 2 1866
失恋的感觉
失恋的感觉 2020-11-27 07:33

I have a collection called article_category which store all article_id belongs to the category with category_id with data format like

2条回答
  •  一向
    一向 (楼主)
    2020-11-27 07:57

    You've couple of things incorrect here. category_id should be all_category_id. Use the join condition in $lookup and move the $match outside of $lookup stage with $unwind for optimized lookup.

    Use $project with exclusion to drop the looked up field from final response. Something like {$project:{article_category:0}}

    Try

    db.article.aggregate([
      {"$match":{"title":{"$regex":/example/}}},
      {"$lookup":{
        "from":"article_category",
        "localField":"article_id",
        "foreignField":"article_id",
        "as":"article_category"
      }},
      {"$unwind":"$article_category"},
      {"$match":{"article_category.all_category_id":8}}
    ])
    

    For uncorrelated subquery try

    db.article.aggregate([
      {"$match":{"title":{"$regex":/example/}}},
      {"$lookup":{
        "from":"article_category",
        "pipeline":[{"$match":{"all_category_id":8}}],
        "as":"categories"
      }},
      {"$match":{"categories":{"$ne":[]}}}
    ])
    

提交回复
热议问题