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

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -