mongodb 分页查询并 根据传入的经纬度计算计算两点距离进行排序

来源:互联网 发布:淘宝上买app store 编辑:程序博客网 时间:2024/06/11 05:23

需求:查询一个表中的多个字段进行分页排序,这其中包括有需要根据查询条件传入的经纬度算出两点距离进行排序的一个功能,如果使用mongodb普通方式可以计算出距离,但是不能根据距离进行排序,所以通过mongodb 的aggregate中提供的geoNear方法进行计算距离,而且aggregate提供了project指定查询指定字段信息, 把计算出来的距离存在一个字段中,取出这个字段进行排序,所有选择了如下代码
                 if (lon == 0 && lat == 0){//没有开gps,默认值为上海市中心lon = 121.491121;lat = 31.243466;}//判断是否按距离排序if(seq == 1 || seq == 0 || seq == 4){//默认排序统一采用综合排序if(seq == 0){seq = 4;}if(lon != 0 && lat != 0){}else{seq=2;}}DBObject sortFileds = new BasicDBObject();DBObject geoNearFileds = new BasicDBObject();geoNearFileds.put("distanceMultiplier", 6378137.0);geoNearFileds.put("near", new double[]{lon,lat});geoNearFileds.put("spherical",true);geoNearFileds.put("distanceField", "distance");geoNearFileds.put("includeLocs", "position");if (nearby!=0) {//选择了附近geoNearFileds.put("maxDistance", nearby);if (seq==0||seq==4) {sortFileds.put("seqScore", -1);sortFileds.put("evalGoodCount", -1);sortFileds.put("distance", 1);if (nearby == 0) {sortFileds.put("seqRating", 1);}sortFileds.put("carNo", 1);}sortFileds = sort(seq, sortFileds);}else{//未选择附近if (seq==0||seq==4) {sortFileds.put("seqRating", -1);sortFileds.put("carNo", 1);sortFileds.put("distance", 1);}else {sortFileds = sort(seq, sortFileds);}} DBObject geoNear = new BasicDBObject("$geoNear", geoNearFileds);DBObject sort = new BasicDBObject("$sort", sortFileds);DBObject match  = new BasicDBObject("$match", criteria.getCriteriaObject());DBObject skip  = new BasicDBObject("$skip",(pageNum-1)*pageSize);DBObject limit  = new BasicDBObject("$limit",pageSize);List<DBObject> dbObjects =  super.aggregate(CarInfo.class, geoNear,match,skip,limit,sort);
原创粉丝点击