0%

MongoDB初体验:Spring中使用MongoTemplate查询数据

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

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

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

CriteriaMongodb说明示例
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.*$"))

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 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

1
2
3
4
5
6
7
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);
明人不说暗话,如果你觉得可以的话,你懂的!