# Spring中使用MongoTemplate查询数据

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

MongoDB Version:3.4.6 spring-data-mongodb Version:1.10.23.RELEASE

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

Criteria Mongodb 说明 示例
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);