参考:https://segmentfault.com/a/1190000007018484
Criteria criteria = new Criteria() {
@Override
public DBObject getCriteriaObject() {
DBObject obj = new BasicDBObject();
obj.put("$where", "this.lastUpdateTime > this.lastReadTime");
return obj;
}
};
我使用的jar是spring-boot-starter-data-mongodb 2.14版本
Criteria的getCriteriaObject()方法,源码是
public Document getCriteriaObject() {
if (this.criteriaChain.size() == 1) {
return criteriaChain.get(0).getSingleCriteriaObject();
} else if (CollectionUtils.isEmpty(this.criteriaChain) && !CollectionUtils.isEmpty(this.criteria)) {
return getSingleCriteriaObject();
} else {
Document criteriaObject = new Document();
for (Criteria c : this.criteriaChain) {
Document document = c.getSingleCriteriaObject();
for (String k : document.keySet()) {
setValue(criteriaObject, k, document.get(k));
}
}
return criteriaObject;
}
}
返回值不一致,可以尝试把Document转成DBObject格式,这个方式就可以用了。
我的解决方式比较简单:
DBObject obj = new BasicDBObject();
obj.put("$where", "this.lastUpdateTime > this.lastReadTime");
Query query = new BasicQuery(obj.toString());
使用这种方式处理 $where 这种格式的条件代码。
加上query.addCriteria(...),就可以多条件操作了。
本文介绍了一种在MongoDB中使用$where条件的解决方案,通过将DBObject转换为Query对象,实现了复杂条件的多条件操作。适用于Spring Boot 2.14版本的数据操作。

1309

被折叠的 条评论
为什么被折叠?



