skip to Main Content

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


  1. Why not execute a query based on the conditions like,

    let showAll = true;
    
    result = showAll ?
        await db.aggregate([]): // no stage will return all
        await db.aggregate([{$match:{ price: 10 }}]);
    
    Login or Signup to reply.
  2. 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:

    const pipeline = [];
    const showAll = true;
    const supressId = true;
    
    if(!showAll){ //< Only if showAll == false
       pipeline.push({ $match: { price: 10 }})
    }
    
    if(supressId){ //< Some other condition etc etc
       pipeline.push({ $project: { _id: 0 } })
    }
    
    const result= await db.aggregate(pipeline);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search