zoukankan      html  css  js  c++  java
  • java使用mongoTemplate去重排序查询

    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.aggregation.TypedAggregation;
    第一种,使用mongoTemplate.findDistinct去重,不支持排序,即使你的query条件带sort排序方法。mongoTemplate.findDistinct去重,会使排序失效。
    优点:查询效率高
    缺点:只返回单一字段。不可多字段返回。不能使用排序,不推荐使用
    Query query = new Query();
    query.addCriteria(Criteria.where("deviceId").is(getListParam.getDeviceId())).with(Sort.by(Sort.Order.desc("startDate")));
    List<RedPacketDeviceRelation> list = mongoTemplate.find(query, RedPacketDeviceRelation.class);
    List<String> activeCodes = mongoTemplate.findDistinct(query, "activeCode", "redPacketDeviceRelation",RedPacketDeviceRelation.class, RedPacketDeviceRelation.class);
    第二种,使用mongoTemplate.aggregate去重,支持排序。推荐使用
    优点:可指定返回类型。支持排序
    缺点:排序是查询效率会变的非常低
    TypedAggregation tagg = TypedAggregation.newAggregation(RedPacketDeviceRelation.class,
             Arrays.asList(
    //筛选条件
    TypedAggregation.match(Criteria.where("deviceId").is(getListParam.getDeviceId())),
    //分组过滤条件,first,as里最后包含展示的字段
    TypedAggregation.group("activeCode").first("activeCode").as("activeCode").first("startDate").as("startDate"),
    //挑选需要字段
              TypedAggregation.project("activeCode", "startDate"),
    //排序字段
    TypedAggregation.sort(Sort.by(Sort.Order.desc("startDate")))
             )
    );
    AggregationResults result111 = mongoTemplate.aggregate(tagg, RedPacketDeviceRelation.class);
    List<RedPacketDeviceRelation> rd = result111.getMappedResults();
    log.debug("排序后的mongoTemplate.group列表1:"+rd);

    第三种,用法和第二种类似
    Aggregation agg = Aggregation.newAggregation(
    // 挑选所需的字段,类似select *,*所代表的字段内容
    Aggregation.project("activeCode", "startDate","packetType"),
    // sql where 语句筛选符合条件的记录
    Aggregation.match(Criteria.where("deviceId").is(getListParam.getDeviceId())),
    // 分组条件,设置分组字段
    Aggregation.group("activeCode").first("activeCode").as("activeCode").first("startDate").as("startDate"),
    // 排序(根据某字段排序 倒序)
    Aggregation.sort(Sort.Direction.DESC,"startDate"),
    // 重新挑选字段
    Aggregation.project("activeCode")
    );
    AggregationResults<JSONObject> results = mongoTemplate.aggregate(agg, "redPacketDeviceRelation", JSONObject.class);
    List<JSONObject> a= results.getMappedResults();
    log.debug("排序后的code列表2:[{}]",results);

    原创文章,引用注明出处:https://www.cnblogs.com/guangxiang/p/12366017.html


  • 相关阅读:
    java中将表单转换为PDF
    base64图片
    ORACLE中用户等系统信息操作
    jquery中live is not a function的问题
    完全卸载Oracle11G
    jquery 获取鼠标和元素的坐标点
    JS的多线程
    Oracle和SQLServer解锁杀进程
    JAVA 通过LDAP获取AD域用户及组织信息
    oracle基础语法大全
  • 原文地址:https://www.cnblogs.com/guangxiang/p/12366017.html
Copyright © 2011-2022 走看看