1

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.

2
  • 1
    you tagged the question with asp.net, php , node.js .. r u sure you tagged correctly ? Commented Apr 9, 2013 at 10:31
  • @rahularyansharma, this requirement is part of my ASP.Net application where we are using Node JS. Tagged with PHP, because most of the PHP developers are using Mongo. Thought I can get suggestions from them too. Commented Apr 9, 2013 at 10:37

1 Answer 1

2

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'.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your reply. If I am not wrong "$in" clause looks for exact matches. I need to get the elements having KeyWords like " very good flat shoes". Looking for KeyWords containing any of the item from array.
Thanks robert. Will try this and let you know.
Robert, I have edited my question with example collection. Modified my collection to have Keywords array. I am trying $in clause query "KeyWords": [{ "$in": searchParams }]. Where searchParams is an array. But it is not retuning any results. In console it is the query is looking like '{ KeyWords: [ { '$in': [Object] } ] }' where Object is the array of string.
You're passing an array as value for the query, but that needs to be an object (so not [{ "$in": searchParams }] but { "$in": searchParams }). Also, $in is case-sensitive: shoes doesn't match SHOES. I edited my answer to make the regular expression search case-insensitive.

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.