Spring Data MongoDB的复杂查询示例 有更新!

 
评论 • 315 浏览

    1、创建一个QueryBuilder

    private QueryBuilder getQueryBuilder(PersonRecordQueryDTO personRecordQueryDTO) {
        log.debug("get personRecords by query : {}", personRecordQueryDTO);
      QueryBuilder queryBuilder = new QueryBuilder();
    
     if (personRecordQueryDTO.getPersonType().equals(PersonType.PERSON_TYPE_STRANGER)) {
            // 陌生人
      queryBuilder.and("isMatched").is(false);
      } else {
            if (personRecordQueryDTO.getPersonType().equals(PersonType.PERSON_TYPE_STAFF)) {
                queryBuilder.and("matched.type").is(PersonType.PERSON_TYPE_STAFF.toString());
      } else {
                queryBuilder.and("matched.type").is(PersonType.PERSON_TYPE_VIP.toString());
      }
            if (Objects.nonNull(personRecordQueryDTO.getName())) {
                queryBuilder.and("matched.name").regex(Pattern.compile("^.*" + personRecordQueryDTO.getName() + ".*$"));
      }
        }
        // 时间条件
      getQueryBuild(personRecordQueryDTO.getStartTime(), personRecordQueryDTO.getEndTime(), queryBuilder);
      if (Objects.nonNull(personRecordQueryDTO.getIps()) && personRecordQueryDTO.getIps().size() != 0) {
            queryBuilder.and("ipc_ip").in(personRecordQueryDTO.getIps());
      }
        log.debug("mongo is : {}", queryBuilder.get());
     return queryBuilder;
    }
    

    2、查询

    public Page getPersonRecords(PersonRecordQueryDTO personRecordQueryDTO, Pageable pageable) {
    QueryBuilder queryBuilder = getQueryBuilder(personRecordQueryDTO);
    //查询结果集条件
    BasicDBObject fieldsObject = new BasicDBObject();
    Query query = new BasicQuery(queryBuilder.get().toString(), fieldsObject.toJson());
    // 总页数
    long total = mongoTemplate.count(query, PersonRecordMongoDB.class);
    //查询结果集
    List list = mongoTemplate.find(query.with(pageable), PersonRecordMongoDB.class);
    //手动分页
    return new PageImpl<>(list, pageable, total);
    }
    

    3、排序

    QueryBuilder queryBuilder = new QueryBuilder();
    if (Objects.nonNull(ipcIds) && !ipcIds.isEmpty()) {
        queryBuilder.and("ipc_ip").in(ipcIds.split(","));
    }
    queryBuilder.and("matched._id").is(personId);
    getQueryBuild(startTime, endTime, queryBuilder);
    Sort sort = new Sort("show_time");
    log.debug("query sql is {}", queryBuilder.get());
    sort.descending();
    //查询结果集条件
    BasicDBObject fieldsObject = new BasicDBObject();
    Query query = new BasicQuery(queryBuilder.get().toString(), fieldsObject.toJson());
    return mongoTemplate.find(query.with(sort), PersonRecordMongoDB.class);
    
    版权声明:本文为博主原创文章,欢迎大家转载,但需保留文章链接。个人博客地址:http://www.wenboblogs.cn
    评论
    validate