0

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?

1 Answer 1

3

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
    ]}
  }
]});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.