mongoDB Join on multiple fields

954 views
Skip to first unread message

N Nandu

unread,
Jul 7, 2016, 6:42:49 AM7/7/16
to mongodb-dev
I am rewriting SQL Queries into mongoDB. Can someone help how do we join two collections with multiple join keys and conditions like in below SQL Query.
SELECT S.* FROM LeftTable S
LEFT JOIN RightTable R ON S.ID =R.ID AND S.MID =R.MID WHERE R.TIM >0 AND S.MOB IS NOT NULL

I have the below code which does with single join key condition. I would be glad if someone can help with multiple join keys and where clause to complete query.

db.dim.aggregate([{$lookup:{from:"dimFactsVer11",localField:"Sub", foreignField:"Type", as:"EmbedUp"}}])
Thank you.

Dwight Merriman

unread,
Jul 13, 2016, 3:40:52 PM7/13/16
to mongodb-dev
for your example, i would suggest doing the lookup on whichever join condition is the more efficient, and then the other match-up as just a filter expression.  

another option is to have a field which is compound, that contains both the ID and the MID.  then you can do it.  i.e., the field could be a subdocument { id : ..., mid : ... } if that were to make sense.  and probably index that field whatever it is on the RHS.

also meta comment and you may already be well aware, but don't bring over the schema verbatim, instead make it more mongodb-style, and transform the data on loading, so that you can do the things you need efficiently.
Reply all
Reply to author
Forward
0 new messages