MongoDB和Java驱动程序:查询中的“忽略大小写”

这是我现在使用的代码,如何添加“忽略大小写”属性?

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

谢谢

当我遇到确切的问题时,我无法通过忽略大小写来查询。 我最终复制了我想要搜索的值,将其标准化。 在这种情况下,您可以创建一个新属性并将其转换为小写,并在其上有一个索引。

编辑:

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

我想知道这是否有效?

如果您使用的是Spring-java,则可以使用不区分大小写的方式进行搜索。

 public List searchQuestionByText(String qText){ Query query = new Query(); query.addCriteria(Criteria.where("discussionName").regex(qText,"i")); return mongoTemplate.find(query, Discussion.class); } 
 db.iolog.find({$where:"this.firstname.toLowerCase()==\"telMan\".toLowerCase()"}); DBObject ref = new BasicDBObject(); ref.append("firstname", new BasicDBObject("$where","this.firstname.toLowerCase()=="+firstname+".toLowerCase()")); 

我也试图充分利用“不区分大小写”的实现。 如果您使用的是MongoDB Java驱动程序3.0或更高版本,则应使用以下代码,并使用$ option参数! 它真的很容易使用:

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

“key”和“value”字段需要使用您自己的数据进行更改。

(我还建议您使用$ regex参数进行搜索,以便在数据库中有越来越多的记录的情况下通过部分匹配来检索信息)。

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