Home > OS >  condition with $or operator in mongodb
condition with $or operator in mongodb

Time:09-28

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

CodePudding user response:

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' }
  ]
}
  • Related