开发者

MongoDB and Java driver: "ignore case" in query

This is th开发者_StackOverflowe code I'm using now, how do I add the "ignore case" attribute?

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

Thanks


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?


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);     
    }


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).


db.iolog.find({$where:"this.firstname.toLowerCase()==\"telMan\".toLowerCase()"});
DBObject ref = new BasicDBObject();
ref.append("firstname", new BasicDBObject("$where","this.firstname.toLowerCase()=="+firstname+".toLowerCase()"));


 mapValue = new HashMap<String, Object>();
 mapValue.put("$options", "i");
 mapValue.put("$regex", "smth");
 searchMap.put("name", mapValue);
 collection.find(new BasicDBObject(searchMap));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜