$lookup
3.6 sintaxe permite juntar tabelas aninhadas e $unwind
to desconstrói um campo de matriz dos documentos de entrada para gerar um documento para cada elemento. Algo assim position.aggregate([
{ "$lookup": {
"from": "companies",
"let": { "companyId": "$company_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$companyId" ] } } },
{ "$lookup": {
"from": "industries",
"let": { "industry_id": "$industry_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$industry_id" ] } } }
],
"as": "industry"
}},
{ "$unwind": "$industry" }
],
"as": "company"
}},
{ "$unwind": "$company" }
])
Com a versão 3.4
position.aggregate([
{ "$lookup": {
"from": "companies",
"localField": "company_id",
"foreignField": "_id",
"as": "companies"
}},
{ "$unwind": "$companies" },
{ "$lookup": {
"from": "industries",
"localField": "companies.industry_id",
"foreignField": "_id",
"as": "companies.industry"
}},
{ "$unwind": "$companies.industry" },
{ "$group": {
"_id": "$_id",
"companies": { "$push": "$companies" }
}}
])