本人在开发过程中,遇到了一些查询MongoDB的业务需求,然后总结了一些 Java MongoDB 查询操作。
$in $lte sort 排序等用法,测试有效。
参数封装成实体,然后查询,之后封装为分页的结果。
利用 BasicDBObject 和 BasicDBList 即可完成 所有的基本查询操作。 包括$in $and $or $gte 等。
@Override
public Page searchByPage(AccidentSearchInRequest accidentSearchInRequest) {
String province = accidentSearchInRequest.getProvince();
DateParam dateParam = accidentSearchInRequest.getDateParam();
String startDate = dateParam.getStartDate();
String endDate = dateParam.getEndDate();
String[] sgjb = accidentSearchInRequest.getSgjb();
String[] atype = accidentSearchInRequest.getAtype();
String order = accidentSearchInRequest.getPage().getOrders().get(0).getOrderBy();
com.topcom.cms.common.page.PageRequest pageRequest = accidentSearchInRequest.getPage();
Integer page = pageRequest.getPage();
Integer limit = pageRequest.getLimit();
BasicDBObject query=new BasicDBObject();//mongodb查询
if (StringUtils.isNotBlank(province)){
query.put("province",province);
}
if (sgjb.length>0){
BasicDBList values = new BasicDBList();
for (int i=0;i<sgjb.length;i++){
values.add(sgjb[i]);
}
BasicDBObject in = new BasicDBObject("$in", values);
query.put("sgjb",in);
}
if (atype.length>0){
BasicDBList values = new BasicDBList();
for (int i=0;i<atype.length;i++){
values.add(atype[i]);
}
BasicDBObject in = new BasicDBObject("$in", values);
query.put("atype",in);
}
query.put("originaltime", new BasicDBObject("$gte", startDate).append("$lte",endDate));
BasicDBObject orderBy = new BasicDBObject(order, -1);
DBCollection collection = MongoDBUtil.getDBCollection("acc");
List<DBObject> queryList = collection.find(query).sort(orderBy).toArray();
//获取pageable的参数的页码,从1开始
int pageNo = page;
//获取pageable的页显示大小
int pageSize = limit;
int fromIndex = pageSize * (pageNo - 1);
int toIndex = pageSize * pageNo;
if (toIndex > queryList.size()) {
toIndex = queryList.size();
}
if (fromIndex > toIndex) {
fromIndex = toIndex;
}
//获取list的分页集合
List<DBObject> result = queryList.subList(fromIndex, toIndex);
//创建page对象,并且可以排序
Page pageResult = new PageImpl(result, new PageRequest(pageNo - 1, pageSize), queryList.size());
return pageResult;
}
测试:
传入参数:
{
"atype": [
"煤矿"
],
"dateParam": {
"endDate": "2018-01-01",
"startDate": "2011-01-01"
},
"page": {
"limit": 5,
"orders": [
{
"direction": "ASC",
"orderBy": "deathnumber"
}
],
"page": 1
},
"province": "山东",
"sgjb": [
"一般事故","较大事故","重大事故"
]
}
结果: 成功!