首页 > 解决方案 > Mongoose 使用 $and 应用相同属性的两个过滤器

问题描述

我有一个状态属性,我只想在状态为 pending时应用日期过滤器,对于其他状态,不需要日期过滤器。

  1. 仅返回添加到“$in”的状态。
  2. 如果状态为待处理,则应用日期过滤器(日期小于当前时间)。

我确实喜欢这个,但它不能正常工作。

   filter = { $and: [ { 
                'package' : {$in: ids}, 
                'status':  {$in: ['pending', 'accepted',  'charged', 'captured']},
                date  
                },
                {
                    $and:[
                        {status : 'pending', date:{$lt:current_time}},
                    ]
                }
            ]
        };

标签: mongoosefilter

解决方案


  • 使用$or代替$and,因为它会满足条件之一
  • pending$in条件中删除状态
  • $and包装package条件和$or条件
filter = {
  $and: [
    { package: { $in: ids } },
    {
      $or: [
        { status: { $in: ["accepted", "charged", "captured"] } },
        {
          status: "pending",
          date: { $lt: current_time }
        }
      ]
    }
  ]
};

操场


推荐阅读