I am trying to join two collections and get fields from both the collections. Collections have very basic structure and this is how they look like:
"products": [
{
"_id": 0,
"name": "product 0",
"desc": "some product",
"sales_reps": [
{
"sales_rep_id": 0,
"is_doing_good": true
},
{
"sales_rep_id": 1,
"is_doing_good": true
}
]
}
]
"sales_rep_master": [
{
"_id": 0,
"name": "sales rep 0"
},
{
"_id": 1,
"name": "sales rep 1"
},
{
"_id": 2,
"name": "sales rep 2"
}
]
I am trying to join them on products.sales_reps.sales_rep_id = sales_rep_master._id. This is how my query looks like:
[
{
"$match": { <--Filter on product._id
"_id": 0
}
},
{
"$unwind": { <-- Expand sales reps array
"path": "$sales_reps"
}
},
{
"$lookup": { <-- join with sales rep master and filter our where is_doing_well is false
"from": "sales_rep_master",
"let": {
"sr_id": "$sales_reps.sales_rep_id",
"is_doing_well": "$sales_reps.is_doing_good"
},
"pipeline": [
{
"$match": {
"$and": [
{
"$expr": {
"$eq": [
"$_id",
"$$sr_id"
]
}
},
{
"$expr": {
"$eq": [
"$$is_doing_well",
true
]
}
}
]
}
},
{
"$addFields": {
"doing_good": "$$is_doing_well"
}
}
],
"as": "sales_reps"
}
},
{
"$unwind": { <<- expand newly created sales reps array
"path": "$sales_reps"
}
},
{
"$group": { <-- Group product and sales reps
"_id": "$_id",
"product": {
"$first": "$$ROOT"
},
"sales_reps": {
"$push": "$sales_reps"
}
},
},
{
"$set": { <-- add sales_reps inside product
"product.sales_reps": "$sales_reps"
}
},
{
"$replaceRoot": { <-- replace root
"newRoot": "$product"
}
}
]
This query is working fine and I am getting expected output but I feel like I am doing something wrong here as this seems to be doing too much just to get fields from two collections. There are more stages after that which I have excluded.
Here is the demo: https://mongoplayground.net/p/_Tz3fm4a-J8
Am I doing something wrong here or this is how it is supposed to be?