环境
java:1.7
mongodb:3.4
前言
本篇记录模糊查询的java
写法;
以下的例子是,以不区分大小写进行模糊匹配为例!
连接数据库
//连接数据库 start
MongoCredential credential = MongoCredential.createCredential("user", "user", "user".toCharArray());
ServerAddress serverAddress;
serverAddress = new ServerAddress("192.168.1.20", 8080);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
@SuppressWarnings("resource")
MongoClient mongoClient = new MongoClient(addrs, credentials);
System.out.println("Connect to database successfully");
//连接数据库 end
简单模糊匹配
写法一、使用mongo语法
MongoDatabase database = mongoClient.getDatabase("user");
MongoCollection<Document> useropRecord = database.getCollection("accountrelation");
Document match = new Document();
match.append("account_name", new Document("$regex", "e000089").append("$options", "i"));
Document first = useropRecord.find(match).first();
System.out.println(first);
结果:
Document{{_id=357409, org_id=114 。。。后面隐私就不显示了
写法二、使用java的模糊规则
MongoDatabase database = mongoClient.getDatabase("gg_user_db");
MongoCollection<Document> useropRecord = database.getCollection("accountrelation");
Document match = new Document();
Pattern p = Pattern.compile("e00002449", Pattern.CASE_INSENSITIVE);
match.append("account_name", p);
Document first = useropRecord.find(match).first();
System.out.println(first);
结果:
Document{{_id=357409, org_id=114 。。。后面隐私就不显示了
$in的模糊查询
写这篇的目的其实就是为了记录这个
假设我这么一个集合
List<String> arrayList = new ArrayList<String>(){{
add("苹果");
add("梨子");
}};
我现在想模糊查询里面的每一个元素;
List<Pattern> lp = new ArrayList<>();
for(String s: arrayList){
Pattern pattern = Pattern.compile(s, Pattern.CASE_INSENSITIVE);
lp.add(pattern);
}
match.appent("keywords", new BasicDBObject("$in", lp));
总结
相比之下,感觉java
自带的模糊匹配视乎更好些!至少$in
的写法,若使用mongodb
目前不知道怎么去写。
参考地址: