Joins in Mongo DB

If you are working in MySQL, you can use joins to match rows between multiple tables. In Mongo DB, however you are working in documents instead of rows, you can still use joins to combine data from 2 different collections.

Here is how you can do it. Let’s say you have 2 collections, users and posts. You want to save user data in each post document so you can know which user created that post.

const userObj = {
    name: "Adnan"
};

await db.collection("users")
    .insertOne(userObj);

const postObj = {
    title: "My first post",
    userId: userObj._id
};

await db.collection("posts")
    .insertOne(postObj);

After that, you will have one document in users collection.

users collection - mongo db joins

And you will have one document in posts collection. That document will have the same user ID as in users collection.

posts collection - mongo db joins

Now in order to fetch all the posts along with the users data, you can run the following query:

const posts = await db.collection("posts")
    .aggregate([
        {
            $lookup: {
                from: "users",
                localField: "userId",
                foreignField: "_id",
                as: "user"
            }
        },
        {
            $unwind: "$user"
        }
    ])
    .toArray();

console.log(posts);

While in traditional way, you use find({}) function, for complex queries like join, you need to use aggregate function. $lookup operator is used to perform a join on multiple collections.

  • from: This tells the collection name whom to perform join with.
  • localField: This is the name of field in current collection, in this case, the current collection is “posts”.
  • foreignField: This is the field in other collection whom you are performing a join operation. In this case, it is “_id” field in “users” collection.
  • as: This is the alias of the object that will be returned as a result of join operation.

By default, the join will return “user” as an array. To convert each to a separate document, you can use $unwind operator. This will deconstruct the array into each document separately. In this case, it will be returning only 1 user as an array, so it will be deconstructed to 1 document only.

posts users joins - mongo db

That’s how you can perform joins in Mongo DB using aggregate and lookup. If you face any issue in performing a join, feel free to contact me.