-3

How do I join 2 collections in mongodb?

I have a field FK_ID in collection2 which reference collection1.

In SQL I used to do

SELECT * FROM collection1 c1 JOIN collection2 c2 on c2.FK_ID = c1.ID

Would this work ?

db.collection1.join(collection2, {collection1.ID:collection2.FK_ID})

or something around theses lines ? Thanks

Community
  • 1
  • 1
jamesb
  • 9
  • 2

2 Answers2

1

No, it doesn't work. MongoDB Does not support joins, you can only query one collection at a time. You need to start thinking in a NoSQL way, in other words, consider using embedded documents, if you can't, then you can use DB References to reference documents. Think NoSQL.

On side note: you can't guess the syntax, read the documentation to know what operations are supported,MongoDB documentation is quite comprehensive

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
0

Basically, you can replace a JOIN with a subselect. While MongoDB doesn't 'support' joins, it does support something that is similar to subselects, only without catastrophically destroying the result's schema (pseudo code):

users = db.users.find({criteria});
posts = db.posts.find({authorId : { $in : users.select(p -> p.id) } });

This will find all users matching criteria and all their posts via $in. Unlike SQL, the results (that map to different classes) won't be smeared in a single result blob, but you get a list of users, and, through a different request, their posts. On the other hand, you might have to store the users in a dictionary and map them to the posts to construct a fully populated domain model in your application code.

It is, however, vital to understand that you should try to avoid queries like that when using NoSQL. Try to denormalize information if possible. For instance, instead of only storing the authorId in a post, also store the authorName. That makes displaying lists of posts easier and faster, but comes at the cost of having to synchronize changes to author names, for example. In other cases, it's even possible to embed information. For instance, tags could be simply a list of strings, i.e.

post { title:"foo", tags:["correct", "battery", "staple", "horse"] }

You can also perform deletes using $in, e.g. db.collection.remove({"_id" : {$in : [ id1, id2, ... ] } });

mnemosyn
  • 45,391
  • 6
  • 76
  • 82