Search code examples
mongodbmatchpipelinelookupaggregation

MongoDB aggregation with 'and' and 'or' and 'in' conditions


{ "$match": { "$and": [ { "is_active": { "$eq": True }},{ "is_delete": { "$eq": False }}] } }

This is my match condition for lookup aggregation and it is working fine.

Now I need to add two more conditions and these are not mandatory fields they may be null or not, I think I need or condition inside, with and condition as top query when I pass abc and xyz, it is working, if I didn't pass both or anyone its failing (not returning proper data).

{ "abc_id" : { "$eq": abc } },{ "xyz_id" : {"$in": [xyz]} }

How can I achieve this? Thanks for inputs.


Solution

  • You can includ or :

    {
      "$match": {
        "$and": [
          { "is_active": { "$eq": True } },
          { "is_delete": { "$eq": False } },
          {
            "$or": [
              { "abc_id": { "$eq": abc } },
              { "xyz_id": { "$in": [xyz] } }
            ]
          }
        ]
      }
    }