The first step is to do the $lookup to get all the information.
lookup_operations = { "$lookup" : {
"from" : "operation" ,
"localField" : "orgId" ,
"foreignField" : "orgId" ,
"as" : "operations" ,
"pipeline" : [ { "$project" : {
"categoryId" : 1 ,
"operationName" : 1 , /* In your original post you shared a redacted document
with a field operationId but not such field exists in your
real documents. The field operationName was the one
that is the closest.
*/
} } ]
} }
This lookup will forward the following document from your sample documents to the next stage.
{
"name": "Popular Diagnostic",
"status": "active",
"username": "popular",
"orgId": "6b40d-1cfd-459f-b086",
"tagline": "To serve is our ultimate goal",
"email": "hello@popular.com" ,
"operations" : [
{
"categoryId": "d1e01-8398-4b61-9363",
"operationName": "Acute Appendicitis\t"
}
]
}
The next stage is a $lookup in category collection. Note that we do not need to $unwind.
lookup_categories = { "$lookup" : {
"from" : "category" ,
"localField" : "operations.categoryId" ,
"foreignField" : "uid" ,
"as" : "categories"
/* You have no field named categoryDetails in your real category collection document,
so I assume you want it all.
*/
} }
This 2nd lookup will produce document like:
{
"name": "Popular Diagnostic",
"status": "active",
"username": "popular",
"orgId": "6b40d-1cfd-459f-b086",
"tagline": "To serve is our ultimate goal",
"email": "hello@popular.com" ,
"operations" : [
{
"categoryId": "d1e01-8398-4b61-9363",
"operationName": "Acute Appendicitis\t"
}
] ,
"categories" : [
{
"orgId": "6b40d-1cfd-459f-b086",
"categoryName": "Appendicectomy",
"serial": 2,
"uid": "d1e01-8398-4b61-9363"
}
]
}
Personally, I stop here as I have all the information. I feel the application layer can deal with the cosmetic of putting the category information with the operation information.
But you could do it on the aggregation pipeline with a $set stage that uses $map on operations to $mergeObjects $$this and the result of $reduce on categories to find the element with the corresponding uid.