json - Mongodb query string array to see if contains keyword -


i doing ecommerce website , have product collection using mongodb. product have 2 fields:

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

now when user tries search products entering keyword, want query documents see if elements of product's taxonomies or attributes contains searching keyword.

let's search keyword 'fa', since product provided above example has 'fashion' taxonomy contains 'fa', product should included in search results. same applies attributes. how may accomplish that?

taxonomies array , attributes array of objects. use combination of $or: , $regex: follows:

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

Comments

Popular posts from this blog

matlab - error with cyclic autocorrelation function -

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

c# - What is a good .Net RefEdit control to use with ExcelDna? -