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);
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.
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.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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
).
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"));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With