1

I have a string, say "string", and a field in a collection, say "name".

I would like to find all the documents whose name is a substring of "string" (it would return for example documents whose name is "str").

I have looked on internet, and I only find the reciprocal, that is for example documents whose name is "string2".

Would someone know please ?

KR Zlotz

2
  • what is your MongoDB version ? Commented Jun 20, 2020 at 16:59
  • 4.2.8. Why do you ask ? Commented Jun 21, 2020 at 17:06

2 Answers 2

1

Recently I wanted to achieve the same in my project query below worked for me

db.find({name:{ $regex: new RegExp("^" + "your string pattern".toLowerCase(), "i") } }) 

Let me know if you find it useful.

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

Comments

0

There is no arbitrary substring match operator in MongDB that I know of, but you could try expressing your condition with $where or $regex.

5 Comments

$where seems to have performance problems (it "requires that the database processes the JavaScript expression or function for each document in the collection").
That's right, the operation you are trying to perform is not very efficient.
And how could $regex be used (I can see how to search field values as "overstrings", but not as substrings)
/a(b(c?))?|((a?)b)?c/ gets you prefixes or suffixes of abc.
OK, but my "overstring" is a PHP variable. I guess that I have to create a PHP function to generate the regex. But it's OK, I have to work now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.