0

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
  • 1
    You need $expr. db.aggregate([{ $match:{ $expr: { $or: [showAll,{$eq:{"price":10}}] } } }]) Commented Jul 8, 2024 at 6:50
  • This question is similar to: MongoDB aggregation - Match input parameter if provided else do not match. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 9, 2024 at 11:55

2 Answers 2

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 }}]);
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.