如何将$ match与条件if-else一起使用?

时间:2019-09-02 12:04:09

标签: node.js mongodb mongoose

所以我想在if councilPeriod not equal to 1 i can use condition where person with same families_id in other person families array showing up else that condition disabled处进行条件查询。

const families = await People.aggregate([
      {
        $unwind: {
          path: '$families'
        }
      },
      { $project: { Ids: '$families._id' } }
    ]);

    const families_id = families.map(function(i) {
      return i.Ids;
    });

    const people = await People.aggregate([
      {
        $project: {
          _id: 1,
          nia: 1,
          name: 1,
          address: 1,
          sector: 1,
          status: 1,
          grazing: 1,
          councilPeriod: 1,
          crtdDiff: { $subtract: [new Date(), '$dateJoined'] },
          sidiDiff: { $subtract: [new Date(), '$dateSidi'] }
        }
      },
      {
        $match: {
          status: 'Active',
          _id: { $nin: families_id },
          grazing: 'Tidak',
          councilPeriod: { $ne: 1 },
          crtdDiff: { $gt: 63072000000 },
          sidiDiff: { $gt: 63072000000 }
        }
      }
    ]);

我希望查询一个具有CouncilPeriod的人不等于1的情况,然后这些家庭也出现,否则相反。谢谢你。

1 个答案:

答案 0 :(得分:0)

您可以在汇总中使用if条件,例如

db.inventory.aggregate(
   [
      {
         $project:
           {
             item: 1,
             discount:
               {
                 $cond: { if: { $ne: [ "$councilPeriod", 1 ] }, then: _anyCondition_, 
                else: _anyCondition_ }
               }
           }
      }
   ]
)

希望您发现它有用。