先说一下文档结构,文档结构比较复杂,储存了大量的实体对象和集合对象。文档结构类似:
{
"_id": ObjectId("5aadf54cd1f9533275115673"),
"sensorAmount": "3",
"userNameForUpdate": "张三",
"problem": [
"问题-导入失败"
],
"littleProblemEntity": {
"littleProblem": "有问题哇",
"startTime": ISODate("2020-12-18T16:27:45.651Z"),
"endTime": ISODate("2020-12-21T16:27:45.651Z")
},
"problemList": [
{
"index": NumberInt("0"),
"bigProblem": "问题-正常",
"startTime": ISODate("2020-08-20T02:32:01.000Z"),
"endTime": ISODate("2020-08-21T02:32:01.000Z")
},
{
"index": NumberInt("2"),
"sensorProblem": "问题-加载失败"
}
]
}
文档中有实体对象,也有集合对象
一.以集合对象里的内容为查询条件
1.现在我们要查询出problemList问题存在并且问题内容为“正常”的数据:
Query query = new Query();
query.addCriteria(Criteria.where("problemList.0").exists(true).andOperator(Criteria.where("problemList.bigProblem").regex("正常")));
problemList.0就可以判断出集合对象是否存在,查询具体集合内的文档只需要集合名.字段名就可以查询
2.查询出littleProblemEntity不为空,并且littleProblem不为“”字符串的数据:
Query query = new Query();
query.addCriteria(Criteria.where("littleProblemEntity").ne(null).andOperator(Criteria.where("littleProblemEntity.littleProblem").ne("")));
二.Query对象加入模糊搜索实现多个or连接查询
将上面的查询进一步增加查询条件,实现更复杂的or连接查询。因为每个Query对象只允许有一个orOperator连接条件,否则会报错:you can’t add a second ‘$or’ expression specified $or
那么我们怎么处理这个问题呢,其实很简单我们可以创建多个Criteria对象,直接上代码:
Criteria c = new Criteria();
Criteria criteriaSearch = new Criteria();
criteriaSearch.orOperator(Criteria.where("problemList.0").exists(true).andOperator(Criteria.where("problemList.bigProblem").regex("正常")));
//模糊搜索
Criteria criteriaKey = new Criteria();
if (StringUtils.isNotBlank(searchKey)){//searchKey是模糊搜索的名称
criteriaKey.orOperator(Criteria.where("userNameForUpdate").regex(Pattern.compile(".*?" + searchKey + ".*?")),
Criteria.where("sensorAmount").regex(Pattern.compile(".*?" + searchKey + ".*?")));
}
c.andOperator(criteriaSearch,criteriaKey);
Query query = Query.query(c);
模糊搜索有一个orOperator查询,然后对于文档集合内容也有一个orOperator查询,使用Criteria的:
public Criteria andOperator(Criteria... criteria) {
BasicDBList bsonList = this.createCriteriaList(criteria);
return this.registerCriteriaChainElement((new Criteria("$and")).is(bsonList));
}
将多个criteriaKey 和criteriaSearch 进行拼接就可以了。
如果对您有帮助欢迎点赞哈,有问题可以留言,看到会第一时间回复大家;