当前位置:   article > 正文

Spring Boot JAVA Mongodb 分组、排序、条件、等

Spring Boot JAVA Mongodb 分组、排序、条件、等

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

在这里插入图片描述

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

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

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

下面是MongoDB String => Int 的代码

// collectionName => 表名
// distance => 字段
 
db.collectionName.find({distance:{$exists:true}}).forEach(function(obj){
	obj.distance =new NumberInt(obj.distance);
	db.collectionName.save(obj);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/287025
推荐阅读
相关标签
  

闽ICP备14008679号