views:

1455

answers:

2

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, cid:444, comment="blah" }
  { uid:12345, cid:888, comment="asdf" }
  { uid:99999, cid: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.

+6  A: 

You have to do it the way you described. MongoDB is a non-relational database and doesn't support joins.

Otto Allmendinger
Seems wrong performance wise coming from a sql server background, but its maybe not that bad with a document db?
TT
+1  A: 

There is a specification that a lot of drivers support that's called DBRef.

DBRef is a more formal specification for creating references between documents. DBRefs (generally) include a collection name as well as an oject id. Most developers only use DBRefs if the collection can change from one document to the next. If your referenced collection will always be the same, the manual references outlined above are more efficient.

Source

Pickels