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("&#40;", "(").replace("&#41;", ")");
        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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

'Boom'

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值