MongoDB模糊查询带括号的数据
MongoDB模糊查询带括号的数据
·
MongoDB模糊查询带括号的数据
首先贴一个Mongo的模糊查询语法:
// 注意有括号是要加转义符的
db.getCollection("PUB_ORG_INFO").find({"ORG_CHI_NAME": /^.*乌鲁木齐普瑞眼科医院\(有限公司\).*$/i})
最近使用MongoDB查询酒店基础静态信息时,碰到了这个问题,最终解决后记录一下,以下为部分代码:
1、对查询字符串转义,以处理输入为regex的特定字符(同时允许输入以数字开头的模糊查询):
HotelUtil类:
/**
* mongo模糊查询 转义工具
*/
public static 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;
}
2、使用Criteria:
HolMidServiceImpl类:
public Page<AggregateHotel> productManagementList(HotelListSearchReq hotelSearchReq, PageVO pageVO) {
int curPage = pageVO.getCurPage(); // 当前页
int rowNum = pageVO.getRowNum(); // 每页多少行
String resId = hotelSearchReq.getResId(); // 酒店id
String cityName = hotelSearchReq.getCityCode(); // 城市
String resGradeId = hotelSearchReq.getResGradeId(); // 星级
String keyword = hotelSearchReq.getKeyword(); // 酒店名称
String protocol = hotelSearchReq.getProtocol(); // 协议酒店
Query query = new Query();
Criteria criteria = new Criteria();
if (StringUtil.isNotBlank(resId)) {
criteria.and("hotelId").is(Long.parseLong(resId));
}
if (StringUtil.isNotBlank(cityName)) {
criteria.and("cityName").is(cityName);
}
if (StringUtil.isNotBlank(resGradeId)) {
criteria.and("hotelStar").is(Long.parseLong(resGradeId));
}
if (StringUtil.isNotBlank(keyword)) {
keyword = keyword.replace("(", "(").replace(")", ")");
String hotelName = HotelUtil.escapeExprSpecialWord(keyword);
criteria.and("hotelName").regex("^.*" + hotelName + ".*$");
}
if (StringUtil.isNotBlank(protocol) && "1".equals(protocol)) {
criteria.and("protocol").is(true);
}
query.addCriteria(criteria);
// 总条数
int total = (int) mongoTemplate.count(query, "collectionName");
query.limit(rowNum);
query.skip((curPage - 1) * rowNum);
List<AggregateHotel> records = mongoTemplate.find(query, AggregateHotel.class, "collectionName");
Page<AggregateHotel> page = new Page<>(curPage, rowNum);
page.setRecords(records);
page.setTotal(total);
return page;
}

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)