遇到的问题
要实现 这样的逻辑
where appid = xxx and (name like 'xxx' or os like 'xxx'or ip like 'xxx')
and time >= 'xxx' and time <= 'xxx'
如何解决
解决核心使用 Criteria[] 数组实现
直接帖代码
@Resource
private MongoTemplate mongoTemplate;
@Override
public List<RaspDO> search(PageRequestParam<RaspDO> raspRequest) {
final String hostname = raspRequest.getData().getHostname();
final String appId = raspRequest.getData().getAppId();
final Criteria criteria = new Criteria();
final Criteria orCriteria = new Criteria();
criteria.and("app_id").is(appId);
Pattern pattern = Pattern.compile("^.*" + hostname + ".*$", Pattern.CASE_INSENSITIVE);
Criteria[] criteriaArray_second = {
new Criteria().and("hostname").regex(pattern),
new Criteria().and("register_ip").regex(pattern),
new Criteria().and("version").regex(pattern),
new Criteria().and("os").regex(pattern),
new Criteria().and("_id").is(hostname)
};
criteria.andOperator(orCriteria.orOperator(criteriaArray_second));
final List<RaspDO> raspDOS = mongoTemplate.find(new Query(criteria), RaspDO.class);
return raspDOS;
}
总结
- 使用Criteria数组或者集合作为参数
- mondb 3+ 版本api做了修改,DbObject对象不好使用
- 后期补充 分页 和大于等会以及排序的功能