一.maven中添加依赖
- spring整合MongoDB
2.spring boot 整合mongodb
org.springframework.boot
spring-boot-starter-data-mongodb
查询
mongoTemplate基于 find 有很多方法,
1,先说,两个基础查询类Query【查询】和Criteria【条件】
Query 查询---
其初始化,newQuery(Criteria),或者newQuery().add(Criteria);
可见,Query基本是和Criteria相互配合使用的,(查询加条件);
如果单单是 new Query(),空的查询,就是默认查询所有了【不添加查询条件】
Criteria crt = Criteria.where("isDel").is(false);
crt.and("type").is("shortStay");
OR = "$or":or条件
AND = "$and":and条件
GT = "$gt":大于操作
GTE = "$gte":大于等于操作
LT = "$lt":小于操作
LTE = "$lte"小于等于操作
NE = "$ne":不等于操作
IN = "$in":in操作
代码如下:
public class ShortStayListInputVo{
.........
@ApiModelProperty(value="排序字段,字段写法同mongodb")
private String sortField;
@ApiModelProperty(value="排序方向:1升序,-1降序")
private String sortDirection;
}
@Service("shortStayOrderServices")
public class ShortStayOrderServices{
public ResponseModel getOrderList(InputParamsparams){
ResponseModel rpm = new ResponseModel;
//查询总数做判断如果为0直接返回数据未查到
long rows = shortStayOrderDao.countOrders(params);
if(rows==0){
rpm.setResponseStatus(ResponseStatus.DataNotFound);
return rpm;
}
}
}
public class ShortStayOrderDao{
public List getOrderList(InputParams params){
Query query = new Query();
query.addCriteria(this.condisAssemble(params.getQueryParam()));
query=this.orderCondiCombin(query,params);
return mongoTemplate.find(query,ShortStayOrder.class);
}
public Query orderCondiCombin(Query query,InputParams params){
List sortField = new ArrayList();
org.springframework.data.domain.Sort.Direction direction = null;
//排序
sortField.add(params.getQueryParam().getSortField());
if("1".equals(params.getQueryParam().getSortField()))
direction = Direction.Asc;
}else if ("-1"){
direction = Direction.DESC;
}else{
direciton = Direction.DESC;
}
}else{
direction = Direction.DESC;
sortField.add("createTime");
}
query.with(new Sort(direction,sortField)).skip(params.getPageIndex()*params.getPageSize()).limit(params.getPageSize());
return query;