Java mongodb复杂多条件查询

引入依赖


     org.springframework.boot
     spring-boot-starter-data-mongodb

添加配置

spring:
  data:
    mongodb:
      uri: mongodb://admin:[email protected]:27017,192.168.1.102:27017/transfer

使用MongoTemplate

@Resource
private MongoTemplate mongoTemplate;

// 创建查询对象
Query query =new Query();

// 设置分页
query.skip(0); //页码
query.limit(10); //每页显示数量

// 创建复合查询对象
Criteria cri = new Criteria();
// 设置条件(注意:设置查询的值类型必须和mongodb中类型一致)
cri.and("status").is("0");   // 类型为String,类似sql中 status = '0'
cri.and("boolRelation").is(0D);   // 类型为Double,类似sql中 boolRelation = 0
cri.and("enforType").regex("01.*");   // 正则表达匹配,类似右模糊查询,sql中 like '01%'
// 时间段查询
try {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	cri.and("receiveTime").gte(sdf.parse(“2019-07-01 10:00:00”)).lte(sdf.parse(“2019-07-16 10:00:00”));   
}catch (Exception e){
	e.printStackTrace();
}
// 如果查询条件一个字段要匹配多个值,类似 and (path like '1001%' or path = '1002' or path like '%1003%')
List orgCriList = new ArrayList<>();   // 创建条件集合
// 添加条件
orgCriList.add(Criteria.where("path").regex("1001.*"));
orgCriList.add(Criteria.where("path").is("1002"));
orgCriList.add(Criteria.where("path").regex(".*1003.*"));
Criteria orgCri = new Criteria();
orgCri.orOperator(orgCriList.toArray(new Criteria[orgCriList.size()]));
// 创建一个查询对象,用于存放and和or条件
Criteria criteria = new Criteria();
criteria.andOperator(cri,orgCri);
// 添加到query中
query.addCriteria(criteria);
//设置排序
List orders = new ArrayList<>();
orders.add(new Order(Direction.ASC, "boolRelation"));
orders.add(new Order(Direction.DESC, "receiveTime"));
// 添加到query中
query.with(Sort.by(orders));
/**
 * 最终的查询条件我用oracle sql表示:
 * status = '0'
 * and boolRelation = 0
 * and enforType like '01%'
 * and receiveTime>=to_date('2019-07-01 10:00:00','yyyy-mm-dd hh24:mi:ss')
 * and receiveTime>=to_date('2019-07-01 10:00:00','yyyy-mm-dd hh24:mi:ss')
 * and (path like '1001%' or path = '1002' or path like '%1003%')
 * order by boolRelation, receiveTime desc
 */

// 统计总数
long count = mongoTemplate.count(query, EnforModel.class);
// 查询返回记录
List records = mongoTemplate.find(query, EnforModel.class);

例子中用到的实体类

package com.js.enfor.manage.model;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.Serializable;
import java.util.Date;

/**
 * 

* @author ycq * @since 2019-07-16 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @Document(collection = "JS_ENFOR_DATA") public class EnforModel implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @Id private String id; /** * 类型 */ private String enforType; /** * 接收时间 */ private Date receiveTime; /** * 是否已关联 */ private Double boolRelation; /** * 状态 */ private String status; /** * 关联时间 */ private Date relationTime; /** * path */ private String path; }

你可能感兴趣的:(Java相关知识)