I want to do a match stage in mongoDB aggregate, and in this match I want to check if a condition exists, use a custom query, and if not, use another custom query. The custom queries are nested fields.
after searching and reading documents , I write this code. But it has an error.
I use MongoDB v4.4 . only this version and cannot switch to other versions.
MongoError: FieldPath field names may not contain ‘.’.
{
$match : {
$expr : {
$cond : {
if: { $eq : [ 'type' , 'country'] },
then: {
$and : [
{ 'countryState.status' : 'Confirmed' },
{ 'countryState.prop' : 'high' },
]
},
else: { },
}
}
}
},
If the ‘type’ field, is equal to country, I want to use the custom query, and if not, only {} query.
I would appreciate anyone can help me, how to this match stage with conditional query.
>Solution :
You are asking for the query to return "this or that", so we should use $or. Borrowing the sample data from @cmgchess playground link, this query should logically do what you want I believe:
db.collection.aggregate([
{
$match: {
$or: [
{
"type": "country",
"countryState.status": "Confirmed",
"countryState.prop": "high"
},
{
"type": {
$ne: "country"
}
}
]
}
}
])