MongoTemplate查询
@Resource
private MongoTemplate mongoTemplate;public <T> List<T> getDataList(String param1, Long param2, Class<T> clazz) {// 构建queryQuery query = constructQuery(param1, param2);// 查询return mongoTemplate.find(query, clazz);
}
关系且
构建 Query
private Query constructQuery(String param1, String param2, String param3) {Query query = new Query();if(!Strings.isBlank(param1)){query.addCriteria(Criteria.where("field1").is(param1));}if(!Strings.isBlank(param2)){query.addCriteria(Criteria.where("field2").is(param2));}if(!Strings.isBlank(param3)){query.addCriteria(Criteria.where("field3").is(param3));}return query;
}
关系或
构建 Query
将所有的查询条件添加到一个 List 中,然后将其转换为一个数组,并将数组传递给 Criteria.orOperator 方法。这样,所有的查询条件将被组合成一个或条件
private Query constructQuery(String param1, String param2, String param3) {List<Criteria> criteriaList = new ArrayList<>();if(!Strings.isBlank(param1)){criteriaList.add(Criteria.where("field1").is(param1));}if(!Strings.isBlank(param2)){criteriaList.add(Criteria.where("field2").is(param2));}if(!Strings.isBlank(param3)){criteriaList.add(Criteria.where("field3").is(param3));}Criteria[] criteriaArray = new Criteria[criteriaList.size()];criteriaList.toArray(criteriaArray);Criteria orCriteria = new Criteria().orOperator(criteriaArray);Query query = new Query(orCriteria);return query;}