使用$ regex查询多个字段的MongoDb

时间:2016-05-18 13:34:57

标签: javascript mongodb meteor

我正在关注Angular Meteor教程,它有以下代码:

<div id="popular">
    <p class="trending-title">Popular Products</p>
    <?php echo do_shortcode('[best_selling_products per_page="4"]'); ?>
</div>

我正在尝试修改selector.name以包含description字段。我已经检查过添加selector.description,但是什么也没做。是否可以修改选择器以包括在将正则表达式与文档的任一字段匹配时搜索多个字段?

1 个答案:

答案 0 :(得分:0)

&#34;要么&#34;您可能需要$or: - 如果您只是将description添加到对象中,那么您最终会得到$and:

在您达到名称和描述标准之前,您的选择器将是:

let selector =
  { $or:
    [
      { $and: [ { public: true }, { public: { $exists: true } } ] },
      { $and: [ { owner: this.userId }, { owner: { $exists: true } }] }
    ]
  };

(请注意let而不是const

为此,您希望$and:附加第二个$or:

if (typeof searchString === 'string' && searchString.length) {
  selector = { $and:
    [ 
      selector,
      { $or:
        [
          { name: { $regex: `.*${searchString}.*`, $options : 'i' }},
          { description: { $regex: `.*${searchString}.*`, $options : 'i' }},
        ]
      }
    ]
  };
}

最后,你应该有一个看起来像这样的对象:

{ $and:
  [ 
    { $or: [ public criteria, owner criteria ] },
    { $or: [ name regex, description regex ] }
  ]
}