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"
}
Department collection having data like below:
{
"_id": "xQQrzRgi8",
"departmentName": "Testing department"
},
{
"_id": "56sgAeKfx",
"departmentName": "HR department"
}
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"
}
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"
},
},
}
])
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
},
},
])
HERE is Query with example: https://mongoplayground.net/p/M4Nn7ud33KL
Happy coding!!!
Top comments (0)