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);
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于