'mongo db aggregate match conditional filteration
say I have 3 models:
1- Project..., target_countries
2- Freelancer..., country
3- Country...
now we have search project page where freelancer can apply for projects/ jobs than match their locations. we have 2 conditions:
1- if project owner has targeted certain countries then we check freelancer location against target_locations...
2- if no target_locations set by the owner then we skip this filter so everyone can see the project.
I need to use aggregate (not find)
here is what I have tried but no luck code sample
sample input: freelancerCountryID= 61c9d2753be49339489583b8
output: main MongoError: unknown top level operator: $cond. If you have a field name that starts with a '$' symbol, consider using $getField or $setField.
Solution 1:[1]
after digging I found the solution with the right syntax
use $expr on top of $cond since we are in a $match statment
$match:{
$expr:{
$cond: {
if: {
$and:[ {$eq: [ '$countryFilterIsActive', "ACTIVE" ]}, {$isArray:'$target_locations'} ]
},
then: { $in: [mongoose.Types.ObjectId(freelancerLocationID),'$target_locations'] },
else: {}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ali |
