'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);
Solution 1:[1]
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
).
Solution 2:[2]
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"));
Solution 3:[3]
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
Solution 4:[4]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wiktor Stribiżew |
Solution 2 | pulu |
Solution 3 | |
Solution 4 | Mihael |