1

for aggregate, $cond can be used to form an if-statement. I'm wonder if there's a similar function for .find()

When I tried using $cond in find(), I get

"unknown top level operator: $cond"

I'm trying to do the following (in pseudo code):

if condition is True:
    set filter for find to thing_1
else:
    set filter for find to thing_2
2
  • why don't you create two different queries and pass it? Commented Mar 29, 2017 at 1:31
  • this whole thing becomes a string and is stored in a database. I'm trying to follow suit and form that one string only. Unless I can use an OR somehow Commented Mar 29, 2017 at 22:06

1 Answer 1

1

If you are on Mongo 3.6 or greater, you could try using the $expr operator. Which would then allow you to use $cond.

$expr Allows the use of aggregation expressions within the query language.

Their example can be found here

db.supplies.find( {
    $expr: {
       $lt:[ {
          $cond: {
             if: { $gte: ["$qty", 100] },
             then: { $divide: ["$price", 2] },
             else: { $divide: ["$price", 4] }
           }
       },
       5 ] }
} )
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Would I be able to use this through the mongodb compass app?

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.