I have 3 collections:
- positions:
+------------------+----------------------+-----------------------+ | position_id | company_id | position_name | +------------------+----------------------+-----------------------+ | 1 | 1 | position 1 | +------------------+----------------------+-----------------------+ | 2 | 2 | position 2 | +------------------+----------------------+-----------------------+
- companies:
+------------------+----------------------+-----------------------+ | company_id | industry_id | company_name | +------------------+----------------------+-----------------------+ | 1 | 1 | company 1 | +------------------+----------------------+-----------------------+ | 2 | 2 | company 2 | +-----------------------------------------------------------------+
- industries:
+------------------+----------------------+ | industry_id | industry_name | +------------------+----------------------+ | 1 | industry 1 | +------------------+----------------------+ | 2 | industry 2 | +------------------+----------------------+
I need to return the following result in one API:
[{
position_id: 1,
position_name: 'position 1',
company: {
company_id: 1,
company_name: 'company 1',
industry: {
industry_id: 1,
industry_name: 'industry 1',
}
}
}, {
position_id: 2,
posiiton_name: 'position 2',
company: {
company_id: 2,
company_name: 'company 2',
industry: {
industry_id: 2,
industry_name: 'industry 2',
}
}
}]
So the code of the pipeline part I can think of is like the following:
const pipelines = [{
$lookup: {
from: 'companies',
localField: 'company_id',
foreignField: 'company_id',
as: 'company',
$lookup: {
from: 'industries',
localField: 'industry_id',
foreignField: 'industry_id',
as: 'industry'
}
}
}]
return positions.aggregate(pipelines);
But this would throw some errors. So what is the correct way to do the nested $lookup in mongodb search?
Thanks in advance!