项目加入MongoDB支持,今天第一次用到,学新东西要做笔记。

org.springframework.data.mongodb.core.query.Criteria

Criteria and (String key)$and并且criteria.and("name")…
Criteria andOperator (Criteria… criteria)$and并且criteria.andOperator(Criteria.where("name")…)…
Criteria orOperator (Criteria… criteria)$or或者criteria.orOperator(Criteria.where("name")…)…
Criteria is (Object o)$is等于criteria.and("name").is("tom")
Criteria ne (Object o)$ne不等于criteria.and("name").ne("tom")
Criteria lt (Object o)$lt小于criteria.and("age").lt(20)
Criteria lte (Object o)$lte小等于criteria.and("age").lte(20)
Criteria gt (Object o)$gt大于criteria.and("age").gt(20)
Criteria gte (Object o)$gte大于等于criteria.and("age").gte(20)
Criteria in (Object… o)$in包含criteria.and("name").in("tom","jerry"…)
Criteria nin (Object… o)$nin不包含criteria.and("name").nin("tom","jerry"…)
Criteria regex(Pattern pattern)$regex模糊查询criteria.and("name").regex(\Pattern.compile("^.*t.*$"))

一些常用的查询示例,做个简单的笔记

// SQL: name not like '张%'
Criteria.where("name").regex(Pattern.compile("^张.*$"));

// SQL: interest like '%球%'
Criteria.where("interest").regex(Pattern.compile("^.*球.*$"));

// SQL: address not like '浙江%'
Criteria.where("address").not().regex(Pattern.compile("^.*浙江.*$"));

// SQL: interest not null and interest != '' and interest = '无'
Criteria.where("interest").is(null).is("").is("无");

// SQL: interest = '户外' or interest = '阅读' or interest = '音乐'
new Criteria().orOperator(
    Criteria.where("interest").is("户外"),
    Criteria.where("interest").is("阅读"),
    Criteria.where("interest").is("音乐"));

// SQL: (address like '%杭州%' and sex = 1) or (address like '%苏州%' and sex = 0)
new Criteria().orOperator(
    Criteria.where("address").regex(Pattern.compile("^.*杭州.*$")).and("sex").is(1),
    Criteria.where("address").regex(Pattern.compile("^.*苏州.*$")).and("sex").is(0));

// SQL: (interest = '户外' and sex = 0) or (interest = '音乐' and sex = 1)
new Criteria().orOperator(
    new Criteria().andOperator(Criteria.where("interest").is("户外"), Criteria.where("sex").is(0)),
    new Criteria().andOperator(Criteria.where("interest").is("音乐"), Criteria.where("sex").is(1)));

复制

org.springframework.data.mongodb.core.query.Query
org.springframework.data.mongodb.core.MongoTemplate

Query query = new Query();
query.addCriteria(criteria);
query.skip(current);
query.limit(size);
query.with(new Sort(Sort.Direction.DESC, "createTime"));
List<Customer> list = this.mongoTemplate.find(query, Customer.class);
long count = this.mongoTemplate.count(query, Customer.class);

转自:https://www.guitu18.com/post/2019/08/23/51.html

12-20 15:43