【问题标题】:Mongodb query string array to see if contains keywordMongodb查询字符串数组看是否包含关键字
【发布时间】:2016-01-31 12:45:58
【问题描述】:

我正在做一个电子商务网站,并使用 Mongodb 收集产品。对于产品,我有 2 个字段:

taxonomies: ['clothes', 'female', 'fashion']
attributes: [{'color': 'red'}, {'size': 'large'}, ...]

现在,当用户尝试通过输入某个关键字来搜索产品时,我想查询文档以查看产品分类或属性的任何元素是否包含该搜索关键字。

假设搜索关键字是“fa”,因为我上面作为示例提供的产品具有包含“fa”的“时尚”分类,因此该产品应该包含在搜索结果中。这同样适用于属性。那么我该如何实现呢?

【问题讨论】:

    标签: arrays json mongodb search


    【解决方案1】:

    Taxonomies 是一个数组,而 attributes 是一个对象数组。使用$or:$regex: 的组合,如下所示:

    var searchRe = /.*fa.*/; // create your regular expression, in this case contains
    db.products.find({ $or: [
      { taxonomies: { $elemMatch: { $regex: searchRe }}},
      { attributes: { $or: [
        { $elemMatch: { color: { $regex: searchRe }}},
        { $elemMatch: { size: { $regex: searchRe }}} // you can add additional attributes to search here
        ]}
      }
    ]});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 2011-05-14
      • 2014-02-09
      • 2022-06-30
      • 2021-12-14
      相关资源
      最近更新 更多