1

i'm new to mongoBD. i have join two table using $lookup. i have two models Posts and Savedpost. I need to compare two field postId and savedBy i check mongoDb documentation for lookup and i try

Posts.aggregate([{
        $lookup: {
            from: Savedpost.collection.name, // collection name in db
            localField: "_id", // Post id from Post collection
            foreignField: "postId", // postId from Savedpost collection
            as: "isSaved"
        },
    }]).exec(function(err, students) {
        res.send(students)
    });

here i compare with only postId but i need to compare both fields postId and savedBy it is possible and how ?

Thank you

Paresh Shiyal
  • 534
  • 4
  • 15

1 Answers1

3

Here is how to $lookup based on two fields:

 db.posts.aggregate([
 {
 $lookup: {
   from: "savedposts",
   let: {
     first: "$_id",
     second: "$savedby"
   },
   pipeline: [
    {
      $match: {
        $expr: {
          $and: [
            {
              $eq: [
                "$postid",
                "$$first"
              ]
            },
            {
              $eq: [
                "$saved",
                "$$second"
              ]
            }
          ]
        }
      }
    }
  ],
  as: "result"
 }
}
])

Explained:

  1. Add two temp variables from the post collection via let
  2. In the lookup pipeline stage match based on the temporary variables to the foreign collection lookup keys.

In the example:

first --> posts._id-->savedposts.postid

second --> posts.savedby-->savedposts.saved

playground

R2D2
  • 9,410
  • 2
  • 12
  • 28