Parth Mittal
Parth Mittal

Reputation: 67

How to perform equi join in mongodb?

I am aware how to use lookup in mongoDB to perform Left join, but is there any possible way of performing equi-join where I get documents only when both the field match?

db.collection1.aggregate([
  {
    $lookup:{
      from: "collection2",
      localField: "fname",
      foreignField: "fname",
      as: "sameFirstName"
    }
  }
]).pretty()

Suppose in the above code, I know that it will perform a left join, matching all the fname in collection1 to fname in collection2 and also returning fname in collection1 which do not have any match in collection2(showing null because its a left outer join). What if I want to do an equi join and return only the result which have same fname in both collections?

Upvotes: 0

Views: 601

Answers (1)

mintekhab
mintekhab

Reputation: 203

Following the $lookup pipeline ,use a $match on the "as" variable in lookup .

db.collection1.aggregate([
   {
     $lookup:{
             from: "collection2",
             localField: "fname",
             foreignField: "fname",
             as: "sameFirstName"
     }
   },
   {"$match":{"sameFirstName":{$ne:[]}}}
 ])

Upvotes: 1

Related Questions