Springboot使用mongoDB,比较两个字段的大小

参考: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(...),就可以多条件操作了。

 

 

 

你可能感兴趣的:(spring)