I have to check a Boolean flag and base on its condition return different data result.
for example I have a collection of books and their prices, normal result of query is prices matching 10, BUT IF showAll flag is true, it needs to return all the records.
let showAll=true;
result= await db.aggregate([{$match:{$or:[showAll,{$eq:{"price":10}}]}}])
the problem is, mongo doesn’t accept none object variable inside its logical operators!
I ended up with this error:
$or/$and/$nor entries need to be full objects.
based on the description and of $or operator from mongodb aggregation it seems to be ok.
https://www.mongodb.com/docs/manual/reference/operator/aggregation/or/
I can fix the problem with using an if clause to check the variable and perform a different query, but it looks jerky and disappointing to repeat a same thing again!
2
Answers
Why not execute a query based on the conditions like,
You should use your programming language to handle this kind of thing with a query builder approach, pushing each pipeline stage into a variable conditionally: