以下為部分代碼片段,供參考。
1: 代碼片段1,用Pattern方式來實作 不區分大小寫的比對(包括精确和模糊比對)
//完全比對
Pattern pattern = Pattern.compile("^張$", Pattern.CASE_INSENSITIVE);
//右比對
Pattern pattern = Pattern.compile("^.*張$", Pattern.CASE_INSENSITIVE);
//左比對
Pattern pattern = Pattern.compile("^張.*$", Pattern.CASE_INSENSITIVE);
//模糊比對
Pattern pattern = Pattern.compile("^.*張.*$", Pattern.CASE_INSENSITIVE);
Query query = Query.query(Criteria.where(fieldName).regex(pattern));
List<SimpleUserInfo> users = mongoTemplate.find(query, SimpleUserInfo.class, classname);
return users;
2、對查詢字元串轉義,以處理輸入為regex的特定字元(同時允許輸入以數字開頭的模糊查詢)。
代碼片段A:
//regex對輸入特殊字元轉義
String escapeExprSpecialWord(String keyword) {
if (StringUtils.isNotBlank(keyword)) {
String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
for (String key : fbsArr) {
if (keyword.contains(key)) {
keyword = keyword.replace(key, "\\" + key);
}
}
}
return keyword;
}
以下部分為controller及repository兩部分核心代碼,在controller中将查詢條件拼裝成 SpringBoot MongoTemplate的Criteria對象
給service\repository處理。
代碼片段B:,criteria對象就是實作對filed1 和 filed2的模糊比對
//m.get("parma1")為前端傳入參數param1
Pattern pattern = Pattern.compile(".*?" + escapeExprSpecialWord(m.get("field1").toString()) + ".*");
Criteria criteria=Criteria.where("field1").regex(pattern);
pattern = Pattern.compile(".*?" + escapeExprSpecialWord(m.get("field2").toString()) + ".*");
criteria.and("field2").regex(pattern);
3. 對于子查詢elemmatch的處理
查詢各文章一直都未成功,不知道怎麼回事,我是采用以下方式解決:
- 映射類中按collection結構設定,對子集不要設定為map而是設定子類
- 查詢中直接使用a.b即可查詢
例:collection結構為{id:XXX,content:XXX,project:{id:XXX,name:XXX}}
代碼片段如下:
public class Ticket extends BaseEntity implements java.io.Serializable {
@Id
private String id;
private String content;
private Project project; //定義Project類以比對collection中的project字段
……
}
class Location{
long id;
String name;
}
//查詢project.id=1的記錄
Criteria.where("project.id").is(1);
//查詢project.name包含武漢的記錄
Criteria.where("project.name").regex(".*?武漢.*"); //如從前端擷取有特定字元的查詢條件或以數字開頭的查詢條件請使用前面說的轉義方法處理