当前位置:   article > 正文

Spring Boot JAVA Mongodb 分组、排序、条件、等_java操作mongodb按条件过滤之后进行分组

java操作mongodb按条件过滤之后进行分组

 需要做一个数据从mongodb 取数据 做分析,同一用户编号下的距离最大的前几名

 

↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑上面是mongo的数据格式↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

  1. Aggregation agg = Aggregation.newAggregation(
  2. // 第一步:挑选所需的字段,类似select *,*所代表的字段内容
  3. Aggregation.project("begin", "end", "userId", "distance"),
  4. // 第二步:sql where 语句筛选符合条件的记录
  5. // Aggregation.match(Criteria.where("userId").is(map.get("userId"))),
  6. // 第三步:分组条件,设置分组字段
  7. Aggregation.group("userId").sum("distance").as("distance"),
  8. // 第四部:排序(根据某字段排序 倒序)
  9. Aggregation.sort(Sort.Direction.DESC,"distance"),
  10. // 第五步:数量(分页)
  11. Aggregation.limit(Integer.parseInt(map.get("pagesCount"))),
  12. // 第刘步:重新挑选字段
  13. Aggregation.project("userId","distance")
  14. );
  15. AggregationResults<JSONObject> results = mongoTemplate.aggregate(agg, "collectionName", JSONObject.class);
  16. List<JSONObject> mappedResults = results.getMappedResults();

之前遇到一个问题 ‘distance’分组完成后 一直返回的‘0’ 没有数据,后来发现“distance”字段是String 类型,要把它转为int 或者double ,Aggregation的sum 才能完成

下面是MongoDB String => Int 的代码

  1. // collectionName => 表名
  2. // distance => 字段
  3. db.collectionName.find({distance:{$exists:true}}).forEach(function(obj){
  4. obj.distance =new NumberInt(obj.distance);
  5. db.collectionName.save(obj);
  6. });

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/287011
推荐阅读
相关标签
  

闽ICP备14008679号