欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

用Java实现MongoDB正则查询小技巧

程序员文章站 2022-05-08 10:04:13
...

用Java实现MongoDB正则查询小技巧: //模糊查询 private BasicDBObject getLikeStr(String findStr) { Pattern pattern = Pa

用Java实现MongoDB正则查询小技巧:

//模糊查询
private BasicDBObject getLikeStr(String findStr) {
Pattern pattern = Pattern.compile("^.*" + findStr + ".*$", Pattern.CASE_INSENSITIVE);
return new BasicDBObject("$regex", pattern);
}

DBObject query = new BasicDBObject();
query.put("real_name", getLikeStr(userName));


//endWith文件扩展名
private BasicDBObject endWithStr(String findStr) {
Pattern pattern = Pattern.compile(findStr + "$", Pattern.MULTILINE);
return new BasicDBObject("$regex", pattern);
}

DBObject query = new BasicDBObject();
query.put("filename", endWithStr(“.pdf”));

用Java实现MongoDB正则查询小技巧