Reputation: 11095
Refer to the code below:
{$or: [
{titleLong: { $regex: regExp } },
{catalog: { $regex: regExp } },
{catalogNbr: { $regex: regExp } }
]}
I am trying to find the documents whose fields match a certain regex expression. For example, there's this document.
{course: {titleLong: "Introduction to analysis of algorithms"},
{catalog: "cs3333"},
{catalogNbr: "3333"}}
and when the user types "intro algo" or "3333" or "cs3333" the document should be returned. I tried /(intro|algo)/gi
but it doesn't work becaue it returns all documents that either have intro
or algo
. Also, the g
options doesn't seem to work. I also found the following regex:
(?=.*\bintro\b)(?=.*\balgo\b).+
But this only finds documents that have words that are exactly like intro
and misses introduction
.
Upvotes: 0
Views: 265
Reputation: 626845
You can use PCRE when you define $regex
. You can return all entries starting with specific words, and use inline options like (?i)
(case insensitive search). Here is an example:
{titleLong: { { $regex: '(?i).*\bintro.*' } }
or entris containing "intro" in any position in the string:
{titleLong: { { $regex: '(?i).*intro.*' } }
Upvotes: 0
Reputation: 174706
Remove the word boundaries present inside the lookahead assertion so that it would do a partial match.
(?=.*intro)(?=.*algo).+
OR
(?=.*intro).*algo.*
And don't forget to turn on the case insensitive modifier i
Include the pattern to match "3333"
or "cs3333"
also.
(?=.*intro).*algo.*|^(?:cs)?3333$
Upvotes: 2