dulan
dulan

Reputation: 1604

Mongodb query string array to see if contains keyword

I am doing an ecommerce website and have a product collection using Mongodb. With the product I have 2 fields:

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

Now when user tries to search products by entering some keyword, I want to query the documents to see if any elements of the product's taxonomies or attributes contains that searching keyword.

Let's say the search keyword is 'fa', since the product I provided above as an example has 'fashion' taxonomy that contains 'fa', this product should be included in the search results. The same applies to attributes. So how may I accomplish that?

Upvotes: 0

Views: 1358

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20226

Taxonomies is an array and attributes is an array of objects. Use a combination of $or: and $regex: as follows:

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
    ]}
  }
]});

Upvotes: 3

Related Questions