Spring Data MongoDB 查询语法
Query 和 Criteria 查询
1
2
3Query query = new Query();
query.addCriteria(Criteria.where("name").is("Eric"));
List<User> users = mongoTemplate.find(query, User.class);支持的查询方法:is, regex, lt, gt, pageable, sort
生成query方法
findByX
1
List<User> findByName(String name);
startinggWith and endingWith
1
2List<User> findByNameStartingWith(String regexp);
List<User> findByNameEndingWith(String regexp);between
1
List<User> findByAgeBetween(int ageGT, int ageLT);
like and orderBy
1
List<User> users = userRepository.findByNameLikeOrderByAgeAsc("A");
JSON Query methods : @Query
1
2
List<User> findUsersByName(String name);支持的查询方法: $regex, $gt, $lt
QueryDSL Queries
4.1 maven
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
28
29
30<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-mongodb</artifactId>
<version>3.6.6</version>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>3.6.6</version>
</dependency>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>
org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor
</processor>
</configuration>
</execution>
</executions>
</plugin>4.2 class
1
2
3
4
5
6
7
8
9
10
11
public class User {
private String id;
private String name;
private Integer age;
// standard getters and setters
}Implement QueryDslPredicateExecutor
1
2
3QUser qUser = new QUser("user");
Predicate predicate = qUser.name.eq("Eric");
List<User> users = (List<User>) userRepository.findAll(predicate);支持的查询方法:is,startinggWith and endingWith, between