mongo 过滤 分组查询

时间:2022-12-03 09:52:22
public List<Map<String,Object>> findHouseOneDetailGroupByResblockId() throws Exception {
//返回一手楼盘信息
List<Map<String,Object>> resblockOneIdList = new ArrayList<Map<String,Object>>();
//设置分组函数,获取楼盘id、房源id、套均总价
GroupBy groupBy = GroupBy
.key("resblockOneId")
.initialDocument("{resblockOneId:'0',houseHighPrice:0.0,houseOneId:'0'}")
.reduceFunction(
"function(doc, prev){ var houseHighPrice = (doc.totalprBegin+doc.totalprEnd)/2;if( houseHighPrice > prev.houseHighPrice){ prev.houseHighPrice=houseHighPrice;prev.resblockOneId = doc.resblockOneId;prev.houseOneId=doc._id;}}")
;
//GroupByResults<MHouseOneDetail> result = mongoTemplate.group(MHouseOneDetail.collectionName, groupBy, MHouseOneDetail.class);

/*Criteria criteria=Criteria.where("status").is(BusinessConstant.RESBLOCKONESTATUS)
.andOperator(Criteria.where("isExhibition").is(BusinessConstant.ISEXHIBITION_YES));
*/
//过滤状态
Criteria criteria=Criteria.where("status").is(BusinessConstant.RESBLOCK_ONE_STATUS)
.and("isExhibition").is(BusinessConstant.ISEXHIBITION_YES);
//执行查询
GroupByResults<MHouseOneDetail> result = mongoTemplate.group(criteria,MHouseOneDetail.collectionName, groupBy, MHouseOneDetail.class);
BasicDBList list = (BasicDBList) result.getRawResults().get("retval");
if(list==null){return null;}
//遍历查询集合
for (int i = 0; i < list.size(); i++) {
BasicDBObject obj = (BasicDBObject) list.get(i);
if(obj!=null){
Map<String,Object> map = new HashMap<String, Object>();
//一手楼盘id
String resblockOneID = obj.get("resblockOneId").toString();
//一手房源id
String houseOneID= obj.get("houseOneId").toString();
//最高房源套均总价
Double houseHighPrice = (Double)obj.get("houseHighPrice");
map.put("resblockOneID",resblockOneID );
map.put("houseOneID",houseOneID);
map.put("houseHighPrice", houseHighPrice);
//添加到集合
resblockOneIdList.add(map);
}
}
return resblockOneIdList;
}