Reputation: 67
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
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