I have two collections in MongoDB and I like to use $lookup to mapping two collections and return specific values.
Job collection
{
"_id": ObjectId("5b0d2b2c7ac4792df69a9942"),
"title": "software engineer",
"categories" : [
ObjectId("5b0d16ee7ac4792df69a9924"),
ObjectId("5b0d47667ac4792df69a9994")
],
"deadline": 2021-05-03T06:29:54.634+00:00
}
job_categories collection:
{
"_id": ObjectId(5b0d16ee7ac4792df69a9924),
"name": "front-end"
}
{
"_id": ObjectId(5b0d47667ac4792df69a9994),
"name": "full-stack"
}
The objectidin job collection categories array matches the _id of job_categories.
how to use $lookup and $project to return the following result.
Expected result:
{
"_id": ObjectId("5b0d2b2c7ac4792df69a9942"),
"title": "software engineer",
"categories" : [
ObjectId("5b0d16ee7ac4792df69a9924"),
ObjectId("5b0d47667ac4792df69a9994")
],
"deadline": 2021-05-03T06:29:54.634+00:00,
"categories_list": [
"front-end",
"full-stack"
]
}
The expected result adds a new filed categories list and the array value reference job_categories collection's namekey value.