How do I perform the SQL Join equivalent in MongoDB?
For example say you have two collections (users and comments) and I want to pull all the comments with pid=444 along with the user info for each.
comments
{ uid:12345, pid:444, comment="blah" }
{ uid:12345, pid:888, comment="asdf" }
{ uid:99999, pid:444, comment="qwer" }
users
{ uid:12345, name:"john" }
{ uid:99999, name:"mia" }
Is there a way to pull all the comments with a certain field (eg. ...find({pid:444}) ) and the user information associated with each comment in one go?
At the moment, I am first getting the comments which match my criteria, then figuring out all the uid's in that result set, getting the user objects, and merging them with the comment's results. Seems like I am doing it wrong.
You have to do it the way you described. MongoDB is a non-relational database and doesn't support joins.
We can merge/join all data inside only one collection with a easy function in few lines using the mongodb client console, and now we could be able of perform the desired query. Below a complete example,
.- Authors:
.- Categories:
.- Books
.- Book lending
.- The magic:
.- Get the new collection data:
.- Response :)
I hope this lines can help you.
As others have pointed out you are trying to create a relational database from none relational database which you really don't want to do but anyways, if you have a case that you have to do this here is a solution you can use. We first do a foreach find on collection A( or in your case users) and then we get each item as an object then we use object property (in your case uid) to lookup in our second collection (in your case comments) if we can find it then we have a match and we can print or do something with it. Hope this helps you and good luck :)
We can merge two collection by using mongoDB sub query. Here is example, Commentss--
Userss--
MongoDB sub query for JOIN--
Get result from newly generated Collection--
Result--
Hope so this will help.
This page on the official mongodb site addresses exactly this question:
http://docs.mongodb.org/ecosystem/tutorial/model-data-for-ruby-on-rails/
You can run SQL queries including join on MongoDB with mongo_fdw from Postgres.