在实际使用 MongoDB 中难免会遇到比较文档中字段和字段间的比较查询,在MongoDB 中 $where 关键字可以实现字段间的比较,实例如下:
// 查询文档中 create_date、last_modify_date 年月相同的数据 db.user.find({"$where":"this.create_date.getYear() == this.last_modify_date.getYear() && this.create_date.getMonth() == this.last_modify_date.getMonth()"}) // 查询文档中 create_date 比 last_modify_date 晚的数据 db.user.find({"$where":"this.create_date.getTime() >= this.last_modify_date.getYear()"})
对应java代码:
Criteria criteria = new Criteria() { public DBObject getCriteriaObject() { DBObject obj = new BasicDBObject(); obj.put("$where", "this.create_date.getYear() == this.last_modify_date.getYear() && this.create_date.getMonth() == this.last_modify_date.getMonth()"); return obj; } }); Query query = new Query(orderCriteria); List<JSONObject> users = userMongoTemplate.find(query, JSONObject.class, "user");
如果使用 spring-data-mongodb 2.1.4 或之后的新版本以上写法就编译不同,其正确写法:
Criteria criteria = new Criteria() { public Document getCriteriaObject() { Document obj = new Document(); obj.put("$where", "this.create_date.getYear() == this.last_modify_date.getYear() && this.create_date.getMonth() == this.last_modify_date.getMonth()"); return obj; } }); Query query = new Query(orderCriteria); List<JSONObject> users = userMongoTemplate.find(query, JSONObject.class, "user");