簡體   English   中英

MongoDB查詢字符串數組以查看是否包含關鍵字

[英]Mongodb query string array to see if contains keyword

我正在做一個電子商務網站,並使用Mongodb收集了產品。 對於產品,我有2個領域:

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

現在,當用戶嘗試通過輸入一些關鍵字來搜索產品時,我想查詢文檔以查看產品分類法或屬性的任何元素是否包含該搜索關鍵字。

假設搜索關鍵字為“ fa”,因為我上面作為示例提供的產品具有包含“ fa”的“時尚”分類法,因此該產品應包含在搜索結果中。 屬性同樣如此。 那我該怎么做呢?

分類法是一個數組,屬性是一個對象數組。 使用$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
    ]}
  }
]});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM