0

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.

2
  • then remove the word boundaries. (?=.*intro)(?=.*algo).+ Commented Apr 7, 2015 at 14:29
  • Remove the first \b to find entries with words starting with the values: (?=.*\bintro)(?=.*\balgo).+ Commented Apr 7, 2015 at 14:30

2 Answers 2

2

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$
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.