Thursday, April 20, 2017

How to query with Pattern / Case insensitive in mongoDB

 This following example is showing how to query the mongoDB with LIKE


BasicDBObject criteria = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
if(firstName != null && firstName.length() > 0) {

//            search the firstName field with case sensitive LIKE operator  
    obj.add(new BasicDBObject("firstName", Pattern.compile(firstName));
}
if(lastName != null && lastName.length() > 0) {

//            search the lastName field with case insensitive LIKE operator
    obj.add(new BasicDBObject("lastName", 
        java.util.regex.Pattern.compile(lastName, Pattern.CASE_INSENSITIVE)));
}        
if(obj != null && obj.size() > 0) {
    criteria.put("$and", obj);            
}




Done!!

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...