Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Mongodb regex query

I have to run this query in Java

 db.Users.find({"name": /^ind/i})

My Java code is

Document findQuery = new Document();
findQuery.append("name", Pattern.compile("/^"+name+"/i"));
FindIterable<Document> iterable = db.getCollection("Users").find(findQuery);

It is not returning any data, I think the above java code is converting

> /^ind/i into "/^ind/i"

Thanks in advance.

Edit:

Based on stribizhev suggestion updated the query and its worked

db.Users.find({"name": {"$regex": /^ind/, "$options": "i"}})

Java code

Document regQuery = new Document();
regQuery.append("$regex", "^(?)" + Pattern.quote(name));
regQuery.append("$options", "i");

Document findQuery = new Document();
findQuery.append("name", regQuery);
FindIterable<Document> iterable = db.getCollection("Users").find(findQuery);
like image 948
Indrajeet Avatar asked Sep 22 '15 10:09

Indrajeet


People also ask

How regex works in MongoDB?

MongoDB provides the functionality to search a pattern in a string during a query by writing a regular expression. A regular expression is a generalized way to match patterns with sequences of characters. MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support.

Does MongoDB use queries?

What is MongoDB Query? MongoDB Query is a way to get the data from the MongoDB database. MongoDB queries provide the simplicity in process of fetching data from the database, it's similar to SQL queries in SQL Database language.

How do I display only one field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


3 Answers

You cannot use regex delimiters in Java Pattern.compile, as there are other means in Java (e.g. flags) to do the same.

To enforce case-insensitive search, use inline modifier (?i). So, use "^(?i)"+Pattern.quote(name) instead of "/^"+name+"/i".

Pattern.quote just escapes all regex metacharacters so that they were treated as literals (same as \Q...\E).

like image 179
Wiktor Stribiżew Avatar answered Oct 20 '22 10:10

Wiktor Stribiżew


I guess there is a more elegant way to do that in Java, by using the provided Filters in the MongoDB Java Driver (version 3 and above):

Document query = new Document("equipment","gloves");

//whatever pattern you need. But you do not need the "/" delimiters
String pattern = ".*" + query.getString("equipment") + ".*";

//find(regex("field name", "pattern", "options"));
collection.find(regex("equipment", pattern, "i"));
like image 8
pulu Avatar answered Oct 20 '22 08:10

pulu


You could use Pattern -and Filters-

Pattern regex = Pattern.compile("ind", Pattern.CASE_INSENSITIVE);
Bson filter = Filters.eq("name", regex);

The object Pattern has some other flags, as you can see here

like image 8
hestellezg Avatar answered Oct 20 '22 08:10

hestellezg