simon
simon

Reputation: 375

condition with $or operator in mongodb

if type is check box it should check with two condition one type is checkbox and status is completed or process it should return output. but if type is radio and status should be completed

How to combine or with $cond condition please guide

db.collection.find({
  $and: [
    {
      $or: [
        {
          "type": "radio"
        },
        {
          "type": "checkbox"
        },
        
      ]
    },
    {
      $cond: {
        if: {
          type: "checkbox"
        },
        then: {
          $or: [
            {
              "status": "completed"
            },
            {
              "status": "process"
            }
          ]
        },
        else: {
          "status": "completed"
        }
      }
    }
  ]
})

https://mongoplayground.net/p/NM7Bp4SAsPl

Upvotes: 0

Views: 467

Answers (1)

deceze
deceze

Reputation: 522626

Too overcomplicated. You want to match documents which:

  • are checkboxen and status is completed or process
  • are radios and status is completed

In other words:

  • process is completed and it's a checkbox or radio
  • process is process and it's a checkbox

So:

{
  $or: [
    { status: 'completed', type: { $in: ['checkbox', 'radio'] } },
    { status: 'process', type: 'checkbox' }
  ]
}

Upvotes: 2

Related Questions