MongoTemplate复合条件查询

分、 排序、按时间查询 

     Query query = new Query();
        //必须条件
        Criteria c = Criteria.where("VINID").is(Map.get(vin));
        //范围条件
        if(!StringUtils.isEmpty(start)&&StringUtils.isEmpty(end)){
            c.and("TIME1").gte(GetTime1(start));
        }else if(StringUtils.isEmpty(start)&&!StringUtils.isEmpty(end)){
            c.and("TIME1").lte(GetTime1(end));
        }else if(!StringUtils.isEmpty(start)&&!StringUtils.isEmpty(end)){

//对同一个属性加两次限制需这样操作
            c.andOperator(
            c.where("TIME1").gte(GetTime1(start)),
            c.where("TIME1").lte(GetTime1(end))
            );
        }
        query.addCriteria(c);
        //总数
        num = (int) mongoTemplate.count(query,CarDataEx.class,"jmevTest");
        System.out.println("总数:"+num);
        ht.put("total", num);
        //分页
        query.skip((page-1)*rows).limit(rows);
        //排序
        query.with(new Sort(Sort.Direction.DESC,"TIME1"));
                //query.with(new Sort(properties));
                rst = mongoTemplate.find(query,CarDataEx.class,"jmevTest");

 

二分组查询

 public Page<CourseDetail> listCourseDetails(QueryCourseDetailModel queryModel) {
​
        //条件一 where gradeId in (集合) and mark=true
        Criteria criteria = Criteria.where("gradeId").in(gradeIds).and("mark").is(true);
​
        if (null != status && status.size() > 0) {
            Criteria criteriaChild = new Criteria();
            //条件二  criteriaChild 条件查询 ( teacherCommentStatus = XX or parentsReplyTeacherStatus =XX  )
            criteriaChild.orOperator(Criteria.where("teacherCommentStatus").in(status), Criteria.where("parentsReplyTeacherStatus").is(replayStatus));
        }
​
        //拼接最后语句 where gradeId in (集合) and mark=true  and ( teacherCommentStatus = XX or parentsReplyTeacherStatus =XX  )
        criteria.andOperator(criteriaChild);

        //分组条件
        GroupBy groupBy = new GroupBy("gradeId")
                .initialDocument("{ count: 0 }")
                .reduceFunction("function (doc,pre){pre.count +=1 ;}");

        //使用 mongoTemplate.group 分组查询
        GroupByResults groupByResults = mongoTemplate.
                group(criteria, "homework", groupBy, Homework.class);

        //获取结果
        BasicDBList list = (BasicDBList) groupByResults.getRawResults().get("retval");
        list.stream().map(map -> {
            BasicDBObject obj = (BasicDBObject) map;
            ......
            return obj;
        }).collect(Collectors.toList());
​
        return list;

        ​}

 

posted @ 2018-07-23 13:46  风好大  阅读(19063)  评论(0编辑  收藏  举报