I’m going to show you how to easily query data across multiple collections in MongoDB shell. Which is almost equal to SQL’s JOIN but not ;)
Assume we have two collections users
and posts
…and let’s say we need to find all the users who have at least one post tagged with oranges.
There are quite a few options to do it in half manual way or with MongoDB v3.2 and new
$lookup operator from aggregation framework,
but here is a pretty simple solution which is easy to remember and it’s a one liner:
Let’s break it down:
First part is just a standard finding users with _id matching values $in a given array db.users.find({_id: {$in:...})
Second part is a sub query which uses JavaScript map() function on the query
cursor and maps results into array of users’ _id
(as we know mongodb query does not return an array of objects, but cursor)
Inside the map() functions we specify a callback functions and what field we want to return from every post object. If we run just the second query we would get an array of users’ _id
So basically under the hood our original query becomes this
Another trick is if we have a case when second query users .FindOne() which returns a singular object instead of cursor, we do not need to use map() function and our query becomes a bit simpler