[ACCEPTED]-MongoDB and Java driver: "ignore case" in query-case-insensitive

Accepted answer
Score: 17

When I had the exact problem, I wasn't able 5 to query by ignoring case. I ended up copy 4 the value that I wanted to search normalizing 3 it. In this case, you can create a new property 2 and convert it to lower case and have an 1 index on that.


DBObject ref = new BasicDBObject();
ref.put("myfield", Pattern.compile(".*myValue.*" , Pattern.CASE_INSENSITIVE));
DBCursor cur = coll.find(ref); 

I wonder if that works?

Score: 9

In case if you are using Spring-java below 2 mentioned is the way you can make it search 1 in case-insensitive manner.

public List<Discussion> searchQuestionByText(String qText){
        Query query = new Query();
        return mongoTemplate.find(query, Discussion.class);     
Score: 6

I was also trying to get the best use of 9 the implementation "case insensitive". If 8 you're using the MongoDB Java driver 3.0 or later, you should use 7 this following code, with the $option parameter 6 ! It's really easy to use:

Document basicQuery = new Document();
basicQuery.append("key", new Document("$regex","value").append("$options","i")); 

The fields "key" and 5 "value" need to be changed with 4 your own data.

(I also advise you to search 3 with $regex parameter in order to retrieve information 2 via partial matching in the case you would 1 have more and more records in the database).

Score: 0
DBObject ref = new BasicDBObject();
ref.append("firstname", new BasicDBObject("$where","this.firstname.toLowerCase()=="+firstname+".toLowerCase()"));


More Related questions