5

I am new to Mongo! Please help me how to do left join in Mongo

Sql Statement :

Select * from TableA left Join TableB 
on (TableA.col1 = TableB.col1 AND TableB.col2 = "ABC")

Please provide me the equivalent Mongo Query!!!

Thanks In Advance !

Raghaven 3534
  • 286
  • 1
  • 5
  • 10
  • 2
    [MongoDB tells you how to join](https://www.mongodb.com/blog/post/joins-and-other-aggregation-enhancements-coming-in-mongodb-3-2-part-1-of-3-introduction) and you can see how to chain in this [duplicate post](https://stackoverflow.com/questions/35813854/how-to-join-multiple-collections-with-lookup-mongodb) – Stephen Oct 26 '17 at 16:03
  • @Raghaven was the answer helpful? Feel free to upvote&accept. – wp78de Mar 27 '18 at 22:49

1 Answers1

7

As of Mongo 3.2, you can do the equivalent to a left outer join with the new $lookup operator added to the aggregation pipeline: https://docs.mongodb.org/master/reference/operator/aggregation/lookup/#pipe._S_lookup

Your query would become something like this:

db.TableB.aggregate([
{
  $match:{col2:"ABC"}
},
{
   $lookup:
   {
       from: "TableA",
       localField: "col1",
       foreignField: "col1",
       as: "aliasForTable1Collection"
   }
}
])
Luke H
  • 3,125
  • 27
  • 31
wp78de
  • 18,207
  • 7
  • 43
  • 71