Checking if a field contains a string

Hi, I need to know how to get all documents which field contains specified string in JAVA.
I know in Mongo shell it look like this: ```
db.users.findOne({“username” : /.son./i});

So, can anyone translate it to java ? ;)

With MongoDB Java driver use the find method - see MongoDB Java Find filter Examples. To build a regex query use the find filter Filters#regex method.

The code can be like this:

String patternStr = ".son.";
Pattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
Bson filter = Filters.regex("username", pattern);
1 Like

I did it just like u did, It works most the time but when I have string in DB for example “example string” and I try to look for “string” it will not find anything. Probably space mess it up.

It is more about Regular Expressions (not Java programming). The character . (dot) essentially matches any character . To make the dot optional append a ? . The question mark makes the preceding token in the regular expression optional.

String patternStr = ".son.?";

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.