第一次写这玩意,以前写完就完事了,其实回头想想丢失了好多东西,今天就和大家分享一下,希望对大家有所帮助
我的需求:分页查询数据,将数据根据不同的thingId进行聚合,统计type字段不同类型的个数进行聚合统计后展示,表结构中会有N个不同的thingId,type字段会有1,2,3,4,5,6,7,8这些种类型
数据库字段如下:
"_id" : ObjectId("5a4c797a9f904950b1d5b392"),
"id" : "1",
"thingId" : "123456444",
"deviceId" : "1234566",
"timestamp" : NumberLong(1514961016000),
"shoppingMallId" : "123456",
"orgId" : "123456",
"orgName" : "洛阳运输公司",
"plateCode" : "豫CN444",
"businessType" : "1",
"type" : "1",
"startLon" : 123.456,
"startLat" : 43.256,
"endLon" : 123.456,
"endLat" : 43.256,
"startTime" : NumberLong(1514961016000),
"endTime" : NumberLong(1514961016000),
"describe" : "",
"jsonParam" : ""
引包如下(为了省事直接复制的,自己根据需要删改即可):
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.mongodb.BasicDBObject; import com.vfy.cws.offline.statistics.data.mongo.page.BaseMongoPageable; import com.vfy.cws.offline.statistics.data.statistics.mapper.VehicleEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationResults; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map;
聚合代码如下:
其中分页这个操作有点多余,分页对象存储了页数和每页条数,也可以直接将这两个字段值传递给聚合函数中的分页处理
if (json.getInteger("pageNumber") != null){ pageable = BaseMongoPageable.setVehicleEventAggregationPageableParams(json); }
public JSONObject queryAggregationDBData(JSONObject json){ Pageable pageable = null; //分页 if (json.getInteger("pageNumber") != null){ pageable = BaseMongoPageable.setVehicleEventAggregationPageableParams(json); } List<VehicleEvent> pageContentslist = null; String plateCode = json.getString("keyWord"); String orgId = json.getString("orgId"); JSONObject jsonObject = null; JSONArray array = getAggregation(orgId,plateCode,pageable); long count = getAggregationCount(orgId,plateCode,pageable); jsonObject=setQueryAggregationResultList(array,count,pageable.getPageNumber(),pageable.getPageSize()); return jsonObject; }
public JSONArray getAggregation(String orgId,String plateCode,Pageable pageable) { Criteria criteria = new Criteria(); if(plateCode.