How to Left Join in MongoDB

MD Aminul Islam Feb 02, 2024
How to Left Join in MongoDB

MongoDB is not a relational database. So you can’t perform any relational operation in MongoDB. But there is a way through which you can perform operations like left join in MongoDB.

In this short article, we’re going to learn how we can perform a left join in MongoDB, and also we are going to take a look at an example relevant to the topic to make it easier.

Left Join in MongoDB

A left join is common in Database Manipulation languages like MySQL, SQLite, etc. Left join means collecting all the data from the left table and only the matched data from the right table, and it is very effective when we compare data from multiple tables at a time in a database.

In MongoDB, there is a keyword name $lookup, which we can use to collect data from another collection. Through this keyword, we can select a collection with the specific field by using the below general syntax.

Syntax:

db.mydata.aggregate([
    { $lookup:
       {
         from: 'Your_Collection_Name',
         localField: 'Local_Field',
         foreignField: 'Foreign_Field',
         as: 'Show_As'
       }
     }
])

Note that you have to check if you are in the right collection. To switch on a specific collection, use the command use YourCollection.

Our example below will demonstrate how we can create a left join in MongoDB.

Example:

db.mydata.aggregate([
    { $lookup:
       {
         from: 'mycollection',
         localField: 'id',
         foreignField: '_id',
         as: 'MainID'
       }
     }
])

After executing the above example command, you will get the below output in your console.

Output:

{ _id: ObjectId("63713371117701ff3d627b56"),
  Name: 'Alen',
  Email: 'abc@gmail.com',
  Year: 2018,
  MainID: [ sl: 0 ] }
{ _id: ObjectId("63713371117701ff3d627b57"),
  Name: 'Max',
  Email: 'max@gmail.com',
  Year: 2017,
  MainID: [ sl: 1 ] }
{ _id: ObjectId("63713371117701ff3d627b58"),
  Name: 'Ethen',
  Email: 'ethen@gmail.com',
  Year: 2019,
  MainID: [ sl: 2 ] }

If you look at the resulting output, you will see a new field added named MainID.

Please note that the commands shown in this article are for the MongoDB database and the command needs to be run on the MongoDB console.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - MongoDB Join