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, ... ] } });