美文网首页
Spring Boot JAVA Mongodb 分组、排序、条

Spring Boot JAVA Mongodb 分组、排序、条

作者: 一叶知秋_038b | 来源:发表于2019-05-21 11:33 被阅读0次

摘自:https://blog.csdn.net/q294807420/article/details/81453700

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();

之前遇到一个问题 ‘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);
});

相关文章

网友评论

      本文标题:Spring Boot JAVA Mongodb 分组、排序、条

      本文链接:https://www.haomeiwen.com/subject/zdvdzqtx.html