June 18, 2021

How to query like joins on 2 collections in mongodb using aggregate keyword

To query like JOINS between 2 collections in mongodb, we need to use $aggregate.

Lets see the example:
 
I have 2 collections, one is Employee and another one is Department.
 Employee Collection  
           {    
             "_id" : 1,    
             "name" : {    
                "first" : "Abhi",    
                "last" : "Dev"    
             },    
             "departmentId" : 2
            },    
            {    
             "_id" : 2,    
             "name" : {    
                "first" : "Abc",    
                "last" : "Agrawal"    
             },    
              "departmentId" : 1 
            },    
            {    
             "_id" : 3,    
             "name" : {    
                "first" : "Dhruv",    
                "last" : "Agrawal"    
             },    
             "departmentId" : 1,    
            }  
           }   

Department Collection  
           {    
             "_id" : 1,    
             "name" : "finance" 
            },    
            {    
             "_id" : 2,    
             "name" : "hr" 
            }
           } 

Now I need to fetch employee details for id 2 along with employee's department name. 

The query would be:

db.employee
    .aggregate([
      { $match: { _id: 2 } },
      {
        $lookup: {
          localField: 'departmentId',
          from: 'department',
          foreignField: '_id',
          as: 'departmentName',
        },
      },
      { $unwind: '$departmentName' }
]).toArray()

The output would be:

	{    
         "_id" : 2,    
         "name" : {    
         	"first" : "Abc",    
         	"last" : "Agrawal"    
         },
         "departmentName": {
            "name": "finance"
         }

Hope it helps.

No comments:

Post a Comment