Java操作mongodb(含分页,精确查询,模糊查询,时间区间,排序)进行查询

mongodb是常用的非关系型数据库,他经常用来存储文本数据,也就是JSON格式的数据。
不废话,直接上代码。注释写的很详细。(有问题留言秒回)

    public Page<Product> listProducts(ProductCond cond) {
        //如前端没传,就默认第一页,前10条
        if(cond.getSize()==null ||  cond.getCurrent() ==null) {
            cond.setSize(1);
            cond.setCurrent(10);
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("data_status").is(1L));
        query.addCriteria(Criteria.where("tenant_id").is(LoginUserContext.getContext().getTenantId()));
        //手动拼接查询参数
        if(StringUtils.isNotBlank(cond.getProductSoleCode())){
            query.addCriteria(Criteria.where("product_sole_code").is(cond.getProductSoleCode()));
        }
        //.regex为模糊查询
        if(StringUtils.isNotBlank(cond.getProductTemplateName())){
            query.addCriteria(Criteria.where("product_template_name").regex(".*?" + cond.getProductTemplateName() + ".*"));
        }
        if(StringUtils.isNotBlank(cond.getProductTypeName())){
            query.addCriteria(Criteria.where("product_type_name").is(cond.getProductTypeName()));
        }
        //设置时间区间
        if(StringUtils.isNotBlank(cond.getStartCreateTime()) && StringUtils.isNotBlank(cond.getEndCreateTime())){
            Date startTime = strToDateLong(cond.getStartCreateTime());
            Date endTime = strToDateLong(cond.getEndCreateTime());
            query.addCriteria(Criteria.where("create_time").gte(startTime).lte(endTime));
        }
        //查全部的条数
        long total = mongoTemplate.count(query,Product.class);
        //手动拼接分页参数+根据创建时间倒叙
        query.skip((cond.getCurrent() - 1L) *cond.getSize()).limit(cond.getSize()).with(Sort.by(Sort.Direction.DESC, "create_time"));

        log.info("查询mongodb产品实例的条件为:{}", query);
        List<Product> userList = mongoTemplate.find(query,Product.class);
        //手动拼接分页结果
        long pages = (long)Math.ceil(total/cond.getSize()) ;
        Page<Product> pageList = new Page<>();
        pageList.setRecords(userList);
        pageList.setTotal(total);
        pageList.setPages(pages);
        pageList.setCurrent(cond.getCurrent());
        pageList.setSize(cond.getSize());
        return pageList;
    }

mongoTemplate可以进行区间查询,MongoRepository反正我是没找到他能区间查询的方法。所以查询推荐使用mongoTemplate进行区间查询。
查询结果:在这里插入图片描述
参考以下内容:
https://blog.csdn.net/weixin_43059031/article/details/100079941
https://blog.csdn.net/a1120467800/article/details/109954145
https://blog.csdn.net/weixin_44216706/article/details/106496298
https://blog.csdn.net/cheryjava/article/details/120655671
https://blog.csdn.net/qq_38359685/article/details/113865582
https://blog.csdn.net/xjx891111/article/details/120371529
https://blog.csdn.net/qq_43718308/article/details/108128461
https://blog.csdn.net/edc0228/article/details/92645396

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java操作MongoDB进行regex模糊查询有以下步骤: 首先,我们需要创建一个MongoClient对象,用于连接到MongoDB数据库。可以使用MongoClient的构造函数指定数据库的地址和端口号,也可以使用MongoClientURI指定完整的连接字符串。 接下来,需要获取到指定的数据库和集合。可以使用MongoClient的getDatabase方法获取数据库对象,使用Database的getCollection方法获取集合对象。需要注意的是,在Java中,MongoDB的集合是懒加载的,只有在需要时才会被创建。 然后,在查询时使用BsonDocument对象指定regex表达式。BsonDocument是MongoDB的文档对象,可以用于构建查询条件。使用BsonDocument的append方法可以添加需要匹配的字段和对应的regex表达式。 最后,使用Collection的find方法执行查询操作,并将查询结果以某种方式展示出来。可以使用MongoDB的游标对象来遍历查询结果集,也可以使用Java的Stream API进行过滤、映射等操作。 以下是一个示例代码,演示了如何进行regex模糊查询: ```java import com.mongodb.client.*; import org.bson.*; import static com.mongodb.client.model.Filters.*; public class Main { public static void main(String[] args) { // 创建MongoClient对象 MongoClient mongoClient = new MongoClient("localhost", 27017); // 获取数据库和集合 MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("users"); // 构建查询条件 BsonDocument query = new BsonDocument(); query.append("name", new BsonRegularExpression("John.*")); // 匹配以John开头的name字段 // 执行查询操作 FindIterable<Document> result = collection.find(query); // 遍历查询结果 for (Document document : result) { System.out.println(document.toJson()); } // 关闭连接 mongoClient.close(); } } ``` 上述代码中,假设数据库名为test,集合名为users。在查询条件中,我们使用了以"John"开头的name字段,查询结果将会匹配到所有以"John"开头的文档,并打印出来。 希望以上内容能够解答您关于Java操作MongoDB的regex模糊查询的问题。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值