Reputation: 2673
I have a string array like ['flat','flat shoes','shoes','black shoes']
.
And mongo collection has a field called called 'KeyWords
' which is a string.
I need to write a query to get the elements with 'KeyWords
' containing any of the items from the string array.
Example collection
{
"KeyWords" : [
"MEN'S SMART SHOES- FIREBACK LEATHER SLIP ON SHOES TAN",
"G670",
"SMART SHOES",
"FIREBACK SHOES",
"SHOES"
]}
{
"KeyWords" : [
"MEN'S SMART SHOES- FIREBACK LEATHER SLIP ON SHOES TAN",
"G670",
"SMART SHOES",
"FIREBACK SHOES",
"SHOES"
]
}
Can anybody suggest how to achieve this.
Upvotes: 1
Views: 852
Reputation: 203534
Use $in
for exact matches:
var keywords = ['flat','flat shoes','shoes','black shoes'];
YourModel.find({ KeyWords: { $in : keywords } }, ...);
For substring matches, you could use a regular expression query:
var regexp = new RegExp("\\b(?:" + keywords.join("|") + ")\\b", "i"); // "i" means case insensitive
YourModel.find({ KeyWords : regexp }, ...);
\b
matches a word-boundary, so the regular expression will match 'very good flat shoes' but not 'very good flatshoes'.
Upvotes: 2