首页 >  mongdb >  mongoTemplate大于小于等于查询

mongoTemplate大于小于等于查询

时间:2023-12-24

涉及到数字查询时,需要用到大于小于等于,MongoDB和mysql不太一样,有自己的一套符号:

一、概括

符号介绍:

$gt ----------- > 

$gte --------- >=

$lt ------------ <

$lte ---------- <=

$ne ---------- != 

$eq ---------- =

二、大于 $get

查询大于18岁的user

public List<JSONObject> testQuery() {
 
Query q= new Query();
 
q.addCriteria(Criteria.where("age").gt(18));
 
return  mongoTemplate.find(q, JSONObject.class,"users");
}

三、小于

查询小于18岁的user

public List<JSONObject> testQuery() {
 
Query q= new Query();
 
q.addCriteria(Criteria.where("age").lt(18));
 
return  mongoTemplate.find(q, JSONObject.class,"users");
}

三、等于与不等于

public List<JSONObject> testQuery() {
 
Query q= new Query();
 
q.addCriteria(Criteria.where("user_name").is("小王"));
 
//q.addCriteria(Criteria.where("age").eq(18));//等于
 
q.addCriteria(Criteria.where("age").ne(18));//不等于
 
return  mongoTemplate.find(q, JSONObject.class,"users");
}

四、综合

查询年龄大于18 小于 26的user

所有需要并操作的都使用andOperator(Criteria ...)来连接,所有需要或操作的都是要orOperator(Criteria ...)来连接

public List<JSONObject> testQuery() {
 
Query q= new Query();
   
        Criteria c = new Criteria();
   
        Criteria c1 = Criteria.where("age").gt(18);

        Criteria c2 = Criteria.where("age").lt(26);

        c.andOperator(c1, c2);
 
q.addCriteria(c);
 
return  mongoTemplate.find(q, JSONObject.class,"users");
}