【问题标题】:Conditional Mongo Filter条件 Mongo 过滤器
【发布时间】:2021-11-20 03:15:36
【问题描述】:

我只在用户希望根据标准过滤时才考虑过滤。

我可以使用 $in 很好地过滤,但是当 $in 过滤器中使用的条件没有提供时,它会抱怨它需要一个数组。用 [] 替换它会导致它返回为空,并且我没有要插入的所有可能值的列表(并且不确定我是否想要)

有什么想法吗?下面的颜色是可选标准。 *如果有一个我可以使用的跳过标志会很好。

 const profiles = await Profile.aggregate([
      {
        $geoNear: {
          ...geoFilter,
        },
      },
      {
        $match: {
          $and: [
            {
              _id: {
                $ne: Profile.castID(req.user.profileID),
              },
              colors: { $in: colors },
            },
          ],
        },
      },
      { $skip: skip },
      { $limit: limit },
    ]);

【问题讨论】:

    标签: node.js arrays mongodb mongoose mongodb-query


    【解决方案1】:

    使用这个:

    var match = { _id: {$ne: Profile.castID(req.user.profileID)} };
    if (typeof colors != "undefined") {
       match.colors = { $in: colors };
    }
    
    Profile.aggregate([
      {
        $geoNear: {
          ...geoFilter,
        },
      },
      { $match: match },
      { $skip: skip },
      { $limit: limit },
    ]);          
    

    您不需要$and,但是如果您有需要使用它的情况

    var match = [{ _id: {$ne: Profile.castID(req.user.profileID)} }];
    if (typeof colors != "undefined") {
       match.push({colors: { $in: colors }});
    }
    
    Profile.aggregate([
      {
        $geoNear: {
          ...geoFilter,
        },
      },
      { $match: {$and: match}},
      { $skip: skip },
      { $limit: limit },
    ]);          
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-15
      • 2018-04-12
      • 2017-06-13
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多