Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB and Java driver: "ignore case" in query

This is the code I'm using now, how do I add the "ignore case" attribute?

DBObject query = new BasicDBObject("prop", value);

Thanks

like image 780
Mark Avatar asked Nov 01 '10 13:11

Mark


3 Answers

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

EDIT:

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

I wonder if that works?

like image 173
Amir Raminfar Avatar answered Oct 13 '22 16:10

Amir Raminfar


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

public List<Discussion> searchQuestionByText(String qText){
        Query query = new Query();
        query.addCriteria(Criteria.where("discussionName").regex(qText,"i"));
        return mongoTemplate.find(query, Discussion.class);     
    }
like image 42
user2775185 Avatar answered Oct 13 '22 15:10

user2775185


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

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

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

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

like image 34
Jaja Avatar answered Oct 13 '22 15:10

Jaja