DEV Community

Cover image for How to get data from two collection in NO SQL Database MongoDB
shivlal kumavat
shivlal kumavat

Posted on

How to get data from two collection in NO SQL Database MongoDB

Like I have two collection first is Employee collection and second is Department collection.

Employee collection having below data:

{
  "_id": "kcXtyaB7jGPw9Ks",
  "name": "Test name",
  "post": "Manager",
  "departmentId": "xQQrzRgi8",
  "dateCreated": "2022-07-12T13:09:16.270Z",
  "dateModified": "2022-07-12T13:09:16.270Z"
},
{
  "_id": "mNkyaB6jGPw7KB",
  "name": "Test2 name",
  "post": "Manager",
  "departmentId": "56sgAeKfx",
  "dateCreated": "2022-07-12T13:09:16.270Z",
  "dateModified": "2022-07-12T13:09:16.270Z"
}
Enter fullscreen mode Exit fullscreen mode

Department collection having data like below:

    {
      "_id": "xQQrzRgi8",
      "departmentName": "Testing department"
    },
    {
      "_id": "56sgAeKfx",
      "departmentName": "HR department"
    }
Enter fullscreen mode Exit fullscreen mode

In response of Employee data we want department name with departmentId like below we want response:

{
    "_id": "kcXtyaB7jGPw9Ks",
    "dateCreated": "2022-07-12T13:09:16.270Z",
    "dateModified": "2022-07-12T13:09:16.270Z",
    "departmentId": "xQQrzRgi8",
    "departmentName": "Testing department",
    "name": "Test name",
    "post": "Manager"
  },
  {
    "_id": "mNkyaB6jGPw7KB",
    "dateCreated": "2022-07-12T13:09:16.270Z",
    "dateModified": "2022-07-12T13:09:16.270Z",
    "departmentId": "56sgAeKfx",
    "departmentName": "HR department",
    "name": "Test2 name",
    "post": "Manager"
  }
Enter fullscreen mode Exit fullscreen mode

For above solution we have to aggregate in MongoDB like below:

Here is Example with Query: https://mongoplayground.net/p/V-SC5pmKQR7

db.Employee.aggregate([
  {
    $lookup: {
      from: "Department",
      localField: "departmentId",
      foreignField: "_id",
      as: "departmentName",
    },
  },
  {
    $set: {
      departmentName: {
        $first: "$departmentName.departmentName"
      },   
    }, 
  }
])
Enter fullscreen mode Exit fullscreen mode

In response of employee data want department name only Instead departmentId Then Query will be like below:

db.Employee.aggregate([
  {
    $lookup: {
      from: "Department",
      localField: "departmentId",
      foreignField: "_id",
      as: "departmentName",
    },
  },
  {
    $set: {
      departmentName: {
        $first: "$departmentName.departmentName"
      },
    },
  },
  {
    $project: {
      departmentId: 0
    },
  },
])
Enter fullscreen mode Exit fullscreen mode

HERE is Query with example: https://mongoplayground.net/p/M4Nn7ud33KL

Happy coding!!!

Top comments (0)