在猫鼬中查找条件 [英] lookup with condition in mongoose

查看:72
本文介绍了在猫鼬中查找条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个收藏.文章和书签.

I have two collections. articles and bookmarks.

{
    _id: "5faa889ade5e0a6326a873d3",
    name: "article 1"
},
{
    _id: "5faa889ade5e0a6326a873d",
    name: "article 2"
}

书签

{
    _id: "5faa889ade5e0a6326a873d1",
    user_id: "5fc7b50da483a66a86aa7e9e",
    model_id: "5faa889ade5e0a6326a873d3"
}

我想加入带有书签的文章.如果用户将文章加为书签.我尝试过的

I want to join article with bookmark. if user bookmarked a article. what i have tried

const aggregate = await Articles.aggregate([{
        $lookup: {
            from: "categories",  
            localField: "category_id",
            foreignField: "_id",
            as: "category_id"
        }
    },
    {

        $lookup: {
            from: "bookmarks",  
            localField: "_id",
            foreignField: "model_id",
            as: "bookmarks"
        }
    }
]);

但是它将不仅为用户书签登录,还为文章提供所有书签.那么我该如何添加条件.

but it will gives all bookmark for the article not only logged in user bookmark. so how can I add a condition.

{ "user_id": objectId(req.user._id) } // logged user id

推荐答案

您可以使用

  • 让我们将localField _id 作为 model_id 变量传递,您可以使用$$引用在查找管道中使用字段,
  • 管道放置 $ match 阶段并匹配您所需的条件和 user_id 条件
    • let to pass localField _id as model_id variable, you can use the field inside lookup pipeline using $$ reference,
    • pipeline to put $match stage and match your required conditions and user_id condition
      {
        $lookup: {
          from: "bookmarks",
          let: { model_id: "$_id" },
          pipeline: [
            {
              $match: {
                $expr: { $eq: ["$$model_id", "$model_id"] },
                user_id: objectId(req.user._id)
              }
            }
          ],
          as: "bookmarks"
        }
      }
    


    MongoDB v3.4

    • $ filter 迭代书签,并根据条件获取过滤的书签
    • $filter to iterate loop of bookmarks and get filtered bookmarks on the base of condition
      {
        $lookup: {
          from: "bookmarks",
          localField: "_id",
          foreignField: "model_id",
          as: "bookmarks"
        }
      },
      {
        $addFields: {
          bookmarks: {
            $filter: {
              input: "$bookmarks",
              cond: { $eq: ["$$this.user_id", objectId(req.user._id)] }
            }
          }
        }
      }
    

    这篇关于在猫鼬中查找条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆