Reputation: 611
I'm trying to search a string in my collection below
{
question: "What is your least favorite thing about living in the USA?",
description: "aaaa"
},
{
question: "What is the saddest thing a casino dealer has seen at their table?",
description: "bbbb"
}
I was able to do so by using
db.questions.aggregate(
[
{ $match: { question_title: { $regex: 'what', $options: "i" } }
]
)
and I received both documents. However, when I use keyword
'what USA'
I don't receive any result. My expected result is
"What is your least favorite thing about living in the USA?"
Can you suggest me a regex that I can use so that I will get a result if any of my keywords match with question document?
Upvotes: 0
Views: 208
Reputation: 3729
Dynamic regex :
1.This regex Not match exact words return result for 'ua what':
var searchString = 'usa what';
var regexStr = '(?i)(:s|' + searchString.split(' ').join('|')+')';
db.getCollection('searchQuestion').aggregate(
[
{ $match: { question: { $regex: regexStr, $options: "i" } } },
]
);
2.For exact match words.
Example :
var searchStringg = 'usa what';
var regexStrr = '\\b' + searchStringg.split(' ').join('\\b|\\b')+'\\b';
db.getCollection('searchQuestion').aggregate(
[
{ $match: { question: { $regex: regexStrr, $options: "i" } } },
]
)
Upvotes: 1
Reputation: 18515
You can use something like this:
db.questions.aggregate([
{ $match: { question: { $regex: '(?i)(:s|usa|what)', $options: "i" } } }
])
This is case insensitive (?i)
match which currently looks for either usa
or what
You can play with the regEx more here
Upvotes: 1