Reputation: 647
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);
Upvotes: 20
Views: 30280
Reputation: 3711
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
Upvotes: 8
Reputation: 255
Most of the answers here are not working for me (maybe not up-to-date MongoDB Java driver). Here is what worked for me:
Document regexQuery = new Document();
regexQuery.append("$regex", ".*" + Pattern.quote(searchTerm) + ".*");
BasicDBObject criteria = new BasicDBObject("name", regexQuery);
DBCursor cursor = collection.find(criteria);
Upvotes: 3
Reputation: 505
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"));
Upvotes: 8
Reputation: 626689
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
).
Upvotes: 9