Mongoose use $and to apply same attribute two filters

Viewed 28

I have a status attribute and I want to apply a date filter only if status is pending, for the other status a date filter is not required.

  1. return only the status added to "$in".
  2. if status is pending apply a date filter (date is less than current time).

I do like this, but it is not working fine.

   filter = { $and: [ { 
                'package' : {$in: ids}, 
                'status':  {$in: ['pending', 'accepted',  'charged', 'captured']},
                date  
                },
                {
                    $and:[
                        {status : 'pending', date:{$lt:current_time}},
                    ]
                }
            ]
        };
1 Answers
  • use $or instead of $and, because it would satisfy one of condition
  • remove pending status from $in condition
  • $and to wrap package condition and $or conditions
filter = {
  $and: [
    { package: { $in: ids } },
    {
      $or: [
        { status: { $in: ["accepted", "charged", "captured"] } },
        {
          status: "pending",
          date: { $lt: current_time }
        }
      ]
    }
  ]
};

Playground

Related