MongoDB and Java driver: “ignore case” in query

匆匆过客 提交于 2019-12-01 00:25:55

问题


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

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

Thanks


回答1:


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?




回答2:


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



回答3:


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




回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/4069340/mongodb-and-java-driver-ignore-case-in-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!